Passing Data Using NotificationCenter in Swift 4 - Swift 4 Tutorials W3Schools


Post Top Ad

27 Oct 2017

Passing Data Using NotificationCenter in Swift 4

Passing data from one view controller to another view controller using Notification Center is an easy way when compared to delegate protocols.

Here we need add observer or listeners for getting new data to load. First we need to send data using post notification method.

Let's take an example, Imagine an object X calls an object Y to perform an action. Once the action is complete, object X should know that Y has completed the task and take necessary action, this can be achieved with the help of Notification Center!

Follow step by step for better understanding.

Here we will pass data from second view controller to first view controller.

Sending Data - Post Notification:

First put some data as follow:

let dataToSend = ["name" : "John", "age" : 25] as [String : Any]

Add the following method for sending above data: NSNotification.Name(rawValue: "newDataToLoad"), object: dataToSend)

Before sending data we need to listen for the above notification using NSNotification.Name.

Data Receiving - Add observer:

Add the following code for listening to new data:

NotificationCenter.default.addObserver(self, selector: #selector(notificationRecevied(notification:)), name: NSNotification.Name(rawValue: "newDataToLoad"), object: nil)

Add the following method to retrieve data:

@objc func notificationRecevied(notification: Notification) {
    let data = notification.object

Remove Observer:

Don't forgot to remove observer on viewWillDisappear() as follow:

NotificationCenter.default.removeObserver(self, name: NSNotification.Name(rawValue: "newDataToLoad"), object: nil)

No comments:

Post a Comment

Post Top Ad