使用 NSNotificationCenter通知中心来完成此功能。
APP在进入后台时会调用AppDelegate 的 applicationDidEnterBackground方法。
所以只要在此方法中通知viewController即可。
所以首先在viewController中的viewWillAppear中添加一个观察者
-(void) viewWillAppear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterBackgroundNotification) name:@"enterBackground" object:nil];
}
然后在 AppDelegate 的 applicationDidEnterBackground方法中通知这个观察者。
- (void)applicationDidEnterBackground:(UIApplication *)application {
[[NSNotificationCenter defaultCenter] postNotificationName:@"enterBackground" object:nil];
}
注意~~
为了防止enterBackground被调用两次,我们需要在 viewWillDisappear中移除观察者
-(void) viewWillDisappear:(BOOL)animated {
[[NSNotificationCenter defaultCenter] removeObserver:self name:@"enterBackground" object:nil];
}