Using NotificationCenter

NotificationCenter is an object that lets you register observers, so that those objects are notified when particular events (notifications) are emitted. When posting a notification to a notification center, only observers registered with that particular notification center will be notified.

For example, on the iOS platform, if you want to be notified when your application will go in the background, you can do it as follows:

self.resignObserver = NotificationCenter.default.addObserver(    forName: NSApplication.willResignActiveNotification,    object: nil,     queue: nil) { (notification) in    print("Application will resign active")}

Don't forget to retain the observer, as you will need to remove it from the notification center ...

Get Hands-On Design Patterns with Swift now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.