7.2. Posting Data to Notification Center

Now, let's open up the SecondScreenViewController.swift file. We need to initialize the Notification Center here as well. Let's add the following code:

//
//  SecondScreenViewController.swift
//  App7
//
//  Created by Sakib Miazi on 5/22/23.
//

import UIKit

class SecondScreenViewController: UIViewController {
    //codes omitted...
    
    //MARK: instantiating the Notification center...
    let notificationCenter = NotificationCenter.default
    
   //codes omitted...

}

Posting data to Notification Center

Now, when the user puts some text in textFieldSendBack, and taps buttonSendBack, we need to fetch the text and post the text to Notification Center. So, let's write the following codes in onButtonSendBackTapped() method:

In notificationCenter.post() method, we are passing two parameters.

  • name: The same identifier we used to observe the data.

  • object: The object we are sending to Notification Center. Here, the object is the text the user puts in.

So now let's look into the whole code of SecondScreenViewController.swift:

Now let's run the app.

Notes:

  • We can use Notification Center to send data between screens.

  • We did not use delegates here. The observer method takes care of that.

  • The Notification Center is just like a separate highway of data, independent of the lifecycle of the screens.

  • It is a great way of data exchange, where you do not have to worry about handling data while carefully taking care of the Navigation Stack.

There is a caveat, though. What if I want to send data from the first screen to the second screen?

  • The Notification Center is Asynchronous, so a real-time data transfer is desirable (almost always, the data transfer happens in real-time), yet not guaranteed.

  • The Notification Center can broadcast data as long as the observer is alive. It cannot send the data before the observer is created or after it is killed.

  • You need to set an observer before you send the data. So, when you create the second screen from the first screen, you logically (according to the lifecycle of a screen) post the data from the first screen even before the second screen is created, and the observer is set. So, even if the data is posted, the observer from the second screen can't receive it.

  • Therefore, to send data from the parent screen to a child screen while creating the child screen, you should use the old way of sending data; usually Notification Center can't deliver the data.

Last updated

Was this helpful?