0
点赞
收藏
分享

微信扫一扫

iOS: 当app从background切换到foreground,如何通知uiviewcontroller

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(applicationDidBecomeActive) name:UIApplicationDidBecomeActiveNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForegroundNotification) name:UIApplicationWillEnterForegroundNotification object:nil];
}

- (void) appWillEnterForegroundNotification{
    NSLog(@"trigger event when will enter foreground.");
}

- (void)applicationDidBecomeActive
{
    [_firstView startScanAnimation];
}



当app从background切换到foreground,会trigger AppDelegate.m的2个方法:applicationWillEnterForegroundand applicationDidBecomeActive

但却不会trigger current view controller的 viewWillAppear and viewDidAppear 方法,那么怎么通知current view呢?

答案是通过在current view controller里把self注册为该event的observer!


1. - (void) viewWillAppear:(BOOL)animated{  
2.     [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appWillEnterForegroundNotification) name:UIApplicationWillEnterForegroundNotification object:nil];  
3. }  
4.   
5.   
6. - (void) appWillEnterForegroundNotification{  
7. "trigger event when will enter foreground.");  
8. }


不过还有3个重要的issues:

1. 必须在view controller的 viewWillDisappear/viewDidDisappear 其中一个方法中remove this observer。这是因为假设从当前view切换到另一个view再返回到该view,又会注册一次为observer,这样当从bgground到foreground时就会trigger 2次observer的方法!

remove observer example:




1. -(void) viewDidDisappear:(BOOL)animated{  
2.     [[NSNotificationCenter defaultCenter] removeObserver:self];      
3. }

那么当event发生时,2个view的trigger method会都被调用。而当view B close (即被destroy)后,则只会trigger view A的。

为什么不在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/3771015/what-method-is-called-when-application-appears-from-background-on-iphone

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




举报

相关推荐

0 条评论