Handling applicationDidBecomeActive - "How can a view controller respond to the app becoming Active?" Handling applicationDidBecomeActive - "How can a view controller respond to the app becoming Active?" ios ios

Handling applicationDidBecomeActive - "How can a view controller respond to the app becoming Active?"


Any class in your application can become an "observer" for different notifications in the application. When you create (or load) your view controller, you'll want to register it as an observer for the UIApplicationDidBecomeActiveNotification and specify which method that you want to call when that notification gets sent to your application.

[[NSNotificationCenter defaultCenter] addObserver:self                                         selector:@selector(someMethod:)                                             name:UIApplicationDidBecomeActiveNotification object:nil];

Don't forget to clean up after yourself! Remember to remove yourself as the observer when your view is going away:

[[NSNotificationCenter defaultCenter] removeObserver:self                                                 name:UIApplicationDidBecomeActiveNotification                                              object:nil];

More information about the Notification Center.


Swift 3, 4 Equivalent:

adding observer

NotificationCenter.default.addObserver(self,    selector: #selector(applicationDidBecomeActive),    name: .UIApplicationDidBecomeActive, // UIApplication.didBecomeActiveNotification for swift 4.2+    object: nil)

removing observer

NotificationCenter.default.removeObserver(self,    name: .UIApplicationDidBecomeActive, // UIApplication.didBecomeActiveNotification for swift 4.2+    object: nil)

callback

@objc func applicationDidBecomeActive() {    // handle event}


Swift 2 Equivalent:

let notificationCenter = NSNotificationCenter.defaultCenter()// Add observer:notificationCenter.addObserver(self,  selector:Selector("applicationWillResignActiveNotification"),  name:UIApplicationWillResignActiveNotification,  object:nil)// Remove observer:notificationCenter.removeObserver(self,  name:UIApplicationWillResignActiveNotification,  object:nil)// Remove all observer for all notifications:notificationCenter.removeObserver(self)// Callback:func applicationWillResignActiveNotification() {  // Handle application will resign notification event.}