Search This Blog

Tuesday, November 1, 2016

iOS Swift. NotificationCenter How to post and receive local notifications

How to transfer data across the application, for example when loading is finished and you need to update displayed information. For that purpose you can use Notification Center and Local Notifications. There are three thing you need:

1. Add Observer
NotificationCenter.default.addObserver(self, selector: #selector(ViewController.updateCountLabel(_:)), 
    name: Notification.Name("UpdateCountLabelObserver"), object: nil)


2. Add function to handle notification
func updateCountLabel(_ notification: Notification) {
    guard let countStr = notification.userInfo?["count"] as? String else {
        return
    }        
    label4.text = "\(countStr)"
}

3. Post notification
let dict = ["count": String(55)]
NotificationCenter.default.post(
    name: Notification.Name("UpdateCountLabelObserver"), object: nil, userInfo: dict)




No comments:

Post a Comment