Objective-C: How to intercept app state change (e.g. back to foreground)

In the app delegate, add the following, in the applicationDidBecomeActive, or in any of the methods that you want to track.

    [[NSNotificationCenter defaultCenter]
     postNotificationName:@"UIApplicationDidReceiveRemoteNotification"
     object:self
     userInfo:nil];

– this will send a notification when the action happens.

In the ViewController.m, register the observer for this notification and create the appropriate selector.

    [[NSNotificationCenter defaultCenter]
     addObserver:self
     selector:@selector(didReceiveRemoteNotification:)
     name:@"UIApplicationDidReceiveRemoteNotification1"
     object:nil];

-(void)didReceiveRemoteNotification:(NSDictionary *)userInfo {
    NSLog(@"%s", __FUNCTION__);
    if (self.isViewLoaded && self.view.window) {
        
    }
}

-(void)viewDidUnload {
    [[NSNotificationCenter defaultCenter]
     removeObserver:self
     name:@"UIApplicationDidReceiveRemoteNotification"
     object:nil];
}

Leave a Reply