Saturday, May 7, 2016

Notifications

Using NotificationCenter you can communicate from one class to another. For example, while executing code in one class you can notify the UI to update something.

Basic Setup

In a separate class you might "post" a notification. In this example I named the post "updateView". Notifications is a 3 step process:

Step 1 - Setup Post Names

 
extension Notification.Name {
    static let updateView = NSNotification.Name("updateView")
}
 

Step 2 - Post Notification

To pass data, you can send a dictionary to the userInfo parameter.
 
var userInfo: [String: String] = ["extraData": "Some extra data"]
userInfo["moreData"] = "Some more data"
NotificationCenter.default.post(name: .updateView, object: self, 
    userInfo: userInfo)
 

Step 3 - Observe Notification

Then in your ViewController you might be "observing" for that particular post called "updateView" in the notification center:
 
override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver
            (forName: .updateView, object: nil, 
             queue: OperationQueue.main) {
        (notification) in
        // Get values from the class that sent the notification
        let poster = notification.object as! ClassThatPostedNotification
        let propertyValue = poster.property

        // Get values from userInfo
        let extraData = notification.userInfo?["extraData"] as! String
        let moreData = notification.userInfo?["moreData"] as! String
    }
}
 

So the ViewController will be observing any post called "updateView" and when it observes a post it calls updateView. I usually name my posts and functions the same name because...well, I am a simple guy. :)

(Swift 4)

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.

SwiftUI Search & Filter with Combine - Part 3 (iOS, Xcode 13, SwiftUI, 2...

In part 3 of the Searchable video series, I show you how to use Combine in #SwiftUI for the search and filter logic connected to the searcha...