Calling method in current view controller from App Delegate in iOS

I have two view controllers (BuildingsViewController and RoomsViewController) that both use a function within the App Delegate called upload. The upload function basically does an HTTP request, and if its successful or unsuccessful, triggers a uialertview. This is working fine.

The part I'm struggling with is from within the app delegate's connectionDidFinishLoading method. I need to be able to basically refresh the current view controller via perhaps viewWillAppear method of that view controller. Inside the viewWillAppear function of each view controller I have code which determines the buttons on the bottom toolbar.

I want the "upload" button in the toolbar of each view controller to automatically be removed when the uploading is done via the app delegate.

I've tried doing [viewController viewWillAppear:YES] from within the connectionDidFinishLoading method of the app delegate, but it never gets called.

I hope I'm clear enough. Any help is greatly appreciated.

Thanks.


Solution 1:

To do the refresh of the view do not call viewWillAppear if the view is already displayed. What you want to do is the following:

When ConnectionDidFinishLoading method is triggered post a notification

[[NSNotificationCenter defaultCenter] postNotificationName:@"refreshView" object:nil];

In your viewController observe for this notification. You do it by adding this code to your init or viewDidLoad method

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshView:) name:@"refreshView" object:nil];

Now implement -(void)refreshView:(NSNotification *) notification method in your viewController to manage your view to your liking.

Solution 2:

If you are targeting iOS 4.0 and later, you can use the window's rootViewController property to get the current view controller.

[window.rootViewController viewWillAppear];

If you want your application to run on versions prior to iOS 4.0, then you could add an instance variable to the application delegate to remember which view controller called the upload method, having the controller send itself as a parameter.

- (void)upload:(UIViewController *)viewController {
    self.uploadingViewController = viewController; // This is the property you add
    ...
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    [self.uploadingViewController viewWillAppear];
    self.uploadingViewController = nil;
}

You should also consider using a different method to reload the buttons, something like reloadButtons, since it is not related to the view appearing in this case. You would then call that method from within viewWillAppear.