当app从background切换到foreground,会trigger AppDelegate.m的2个方法:applicationWillEnterForeground and applicationDidBecomeActive
但却不会trigger current view controller的 viewWillAppear and viewDidAppear 方法,那么怎么通知current view呢?
答案是通过在current view controller里把self注册为该event的observer!
- (void) viewWillAppear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForegroundNotification) name:UIApplicationWillEnterForegroundNotification object:nil];
}
- (void) appWillEnterForegroundNotification{
NSLog(@"trigger event when will enter foreground.");
}
不过还有3个重要的issues:
1. 必须在view controller的 viewWillDisappear/viewDidDisappear 其中一个方法中remove this observer。这是因为假设从当前view切换到另一个view再返回到该view,又会注册一次为observer,这样当从bgground到foreground时就会trigger 2次observer的方法!
remove observer example:
-(void) viewDidDisappear:(BOOL)animated{
[[NSNotificationCenter defaultCenter] removeObserver:self];
}
2. 从view A切换到view B,2个view都注册了from bg to fg的observer,那么当event发生时,2个view的trigger method会都被调用。而当view B close (即被destroy)后,则只会trigger view A的。
3. 为什么不在didLoad里add observer?其实是可以的,但有时不适合。例如,view A是root view,在didLoad method里add observer,由于切换到其他view会remove observer,那么当再返回view A时则不会再调用didLoad来add observer。
例子参考WillEnterForegroundNotificationDemo project.
rel links:
http://stackoverflow.com/questions/3445268/respond-to-applicationwillenterforeground-in-a-uiview
http://stackoverflow.com/questions/6103616/alter-view-before-applicationwillenterforeground
http://stackoverflow.com/questions/7569187/changing-uiview-when-applicationwillenterforeground-fires