There are two ways to capture application transitioning to foregorund/background and inactive/active. Lets take the event received when app transitions to the inactive state as an example.
- Implement the corresponding AppDelegate method - applicationWillResignActive(_:)
func applicationWillResignActive(_ application: UIApplication) {
Log("applciationWillResignActive(_:)")
}
- Register for willResignActiveNotification during startup
NotificationCenter.default.addObserver(forName:UIApplication.willResignActiveNotification, object: nil, queue: .main) { (broadcastNotification: Notification) in
Log("Received " + String(describing: broadcastNotification.name))
}
When I tested in code, both works. First, the applicationWillResignActive(_:) delegate method is invoked and then, willResignActiveNotification is received (as mentioned in the documentation).
But I'm unable to decide which to use... even after reading their documentation. What is the recommendation? If both are fine, then there are two different ways to achieve the same thing... there's gotta be some purpose, right?
Both are fine.
Sometimes, arranging the "plumbing" to get from your App Delegate to the place where the notification is needed can be tedious; you end up adding methods to a pile of intermediate objects to pass on the notification. (The "dependency injection" problem). In that case, using the notification center is easier.