Question

Hello I do not have very much programming experience and I'm trying to call a method when the user leaves the app. I know that I am going to use the app delegate methods applicationDidEnterBackground, but how do I make that call a method that is in my ViewController class?

Thanks so much for any help!

ViewController.h:

#import <UIKit/UIKit.h>
@interface ViewController : UIViewController <ADBannerViewDelegate>
{
//Images and buttons
}

-(void)stop;
@end
Was it helpful?

Solution

You can use a notification here. Create a listener for this notification in the viewDidLoad of the viewController and assign the function to it. eg:

in yourView controller add the following in the viewDidLoad

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(notificationEnabled) name:UIApplicationDidEnterBackgroundNotification object:nil];

OTHER TIPS

You can either

  1. observe UIApplicationDidEnterBackgroundNotification inside your ViewController, or

  2. invoke your ViewController method inside appDelegates applicationdidEnterBackground: method. App delegate should have a pointer that points to the rootViewController, ie: your ViewController

goodluck!

edit:

...
-(void)applicationDidEnterBackground:(UIApplication *)application {

UIViewController *uvc= [UIApplication sharedApplication].keyWindow.rootViewController;

ViewController *myvc = (ViewController*) uvc;
[myvc stop];

}
.

When you close or leave your App, AppDelegate methods automatically called, you not need to call them in some specific ViewController.

For doing something when your App is in background you can implement your logic in AppDelegate's applicationDidEnterBackground: method.

Or if your App is not running(means closed) AppDelegate Method didFinishLaunchingWithOptions: is called.

I didn't get the purpose of calling the method inside UIViewController. Eventhough you can create an instance of your viewcontroller inside applicationDidEnterBackground and call the corresponding method in viewcontroller using that object

you can do this by creating an instance of that View and then calling specific method of that view

otherwise if your view is opened then you can find it by follwing code & then call specific method by using that obj as follow in your applicationDidEnterBackground

NSArray *AllViewControllers = [self.navigationController viewControllers];

for (UIViewController *aViewController in AllViewControllers) {
    //NSLog(@" >> Nav Stack  %@", [aViewController class]);
    if ([aViewController isKindOfClass:[YourViewController class]]) {
        [(YourViewController *)aViewController yourMethodToCall];
        break;
    }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top