Application lifecycle - AppDelegate method Vs Notification Center

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.

func applicationWillResignActive(_ application: UIApplication) {
        
    Log("applciationWillResignActive(_:)")
}
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?

Answered by endecotp in 763197022

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.

Accepted Answer

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.

Example please?

Say you've got a class Foo whose instances needs to do something when the app enters/leaves the background. So you add enterBackground and leaveBackground methods to Foo. Those need to be called from the appropriate app delegate methods.

But the Foo instances spread around your app are members of other classes that are themselves members of other classes. In order to call Foo's enterBackground and leaveBackground methods, all of those parent classes need to have enterBackground and leaveBackground methods which are called by their parents and which call their children. If you add a Foo somewhere new, you have to add "plumbing" through all of its parent classes to the top of your object hierarchy so that its enterBackground and leaveBackground methods can be called.

It's better not to do this, and to find some other way of connecting the Foo instances to the events. The NotificationCenter is an example of another way. It is not without its problems though; for example, unit testing is more difficult when a class has "back door" interfaces such as listening to global notifications.

Application lifecycle - AppDelegate method Vs Notification Center
 
 
Q