How to tell when controller has resumed from backg

2020-02-05 03:49发布

So I want to support app switching in my upcoming iPhone app and I've implemented all the proper delegate methods in my application delegate. So when the user resumes the application, I can see their activity in the NSLog and all. However, how can I tell my app has resumed a controller? Is there a method I can put in my controller to tell me the app has resumed in said controller? Reason I ask is because my application handles its own URL schema, and I want to update the view depending on the URL launched. Any help will be greatly appreciated.

Thanks in advance

3条回答
够拽才男人
2楼-- · 2020-02-05 04:05

For Swift 4.2:

 NotificationCenter.default.addObserver(self,
 selector: #selector(appWillEnterForeground),
 name: UIApplication.willEnterForegroundNotification, 
 object: nil)



@objc func appWillEnterForeground() {
    // run when app enters foreground
}
查看更多
神经病院院长
3楼-- · 2020-02-05 04:18

You can have you your controller observe the UIApplicationWillEnterForeground notification. It probably would look something like this:

- (void) viewDidLoad
{
    [super viewDidLoad];
    //do stuff here
    if(&UIApplicationWillEnterForegroundNotification) { //needed to run on older devices, otherwise you'll get EXC_BAD_ACCESS
        NSNotificationCenter *notificationCenter = [NSNotificationCenter defaultCenter];
        [notificationCenter addObserver:self selector:@selector(enteredForeground:) name:UIApplicationWillEnterForegroundNotification object:nil];
    }


}
- (void)enteredForeground:(NSNotification*) not
{
    //do stuff here
}
查看更多
啃猪蹄的小仙女
4楼-- · 2020-02-05 04:32

You can also just override - (void)applicationDidBecomeActive:(UIApplication *)application in the app delegate to have it do whatever you want it to do when it comes back from the background. If you want a particular view to get the message rather than the app delegate you need to register for the notification as described by Elfred above.

查看更多
登录 后发表回答