【问题标题】:How to tell when controller has resumed from background?如何判断控制器何时从后台恢复?
【发布时间】:2011-04-01 22:38:54
【问题描述】:
所以我想在我即将推出的 iPhone 应用程序中支持应用程序切换,并且我已经在我的应用程序委托中实现了所有正确的委托方法。因此,当用户恢复应用程序时,我可以在 NSLog 和所有内容中看到他们的活动。但是,我怎样才能知道我的应用程序已恢复控制器?有没有一种方法可以在我的控制器中告诉我应用程序已在所述控制器中恢复?我问的原因是因为我的应用程序处理自己的 URL 架构,并且我想根据启动的 URL 更新视图。任何帮助将不胜感激。
提前致谢
【问题讨论】:
标签:
iphone
ios4
multitasking
【解决方案1】:
您可以让您的控制器观察UIApplicationWillEnterForeground 通知。它可能看起来像这样:
- (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
}
【解决方案2】:
对于 Swift 4.2:
NotificationCenter.default.addObserver(self,
selector: #selector(appWillEnterForeground),
name: UIApplication.willEnterForegroundNotification,
object: nil)
@objc func appWillEnterForeground() {
// run when app enters foreground
}
【解决方案3】:
您也可以在应用程序委托中覆盖- (void)applicationDidBecomeActive:(UIApplication *)application,让它在它从后台返回时执行您希望它执行的任何操作。如果您希望特定视图而不是应用委托来获取消息,则需要按照上述 Elfred 所述注册通知。