How can I use applicationDidBecomeActive in UIViewController?
Swift 3:
NotificationCenter.default.addObserver(
self,
selector: #selector(applicationDidBecomeActive(_:)),
name: NSNotification.Name.UIApplicationDidBecomeActive,
object: nil)
func applicationDidBecomeActive(_ notification: NSNotification) {
// do something
}
Note: Don't forget to remove the observer
Here is an example of registering a notification handler in Swift (adapted from Apurv's answer above):
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(
self,
selector: #selector(applicationDidBecomeActive(notification:)),
name: NSNotification.Name.UIApplicationDidBecomeActive,
object: nil)
}
@objc func applicationDidBecomeActive(notification: NSNotification) {
// do something
}
Update for Swift 4.2
:
override func viewDidLoad() {
super.viewDidLoad()
NotificationCenter.default.addObserver(self, selector: #selector(applicationDidBecomeActive), name: UIApplication.didBecomeActiveNotification, object: nil)
}
@objc func applicationDidBecomeActive(notification: NSNotification) {
// Application is back in the foreground
print("active")
}
At the time of reactivation, if you want to carry a particular thing for a view controller, you should register a notification in its viewDidLoad
method.
UIApplicationDidBecomeActiveNotification
will automatically notify your application and given controller, if they registered for it.
[[NSNotificationCenter defaultCenter]addObserver:self
selector:@selector(yourMethod)
name:UIApplicationDidBecomeActiveNotification
object:nil];