7.1. Add an Observer

We are sending data from the second screen to the first screen. So, we need to observe the Notification Center for any notifications sent from the Second Screen.

Initializing the Notification Center

We initialize the notification center in the first screen by adding the following line of code in ViewController.swift:

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

import UIKit

class ViewController: UIViewController {
    let firstScreen = FirstScreenView()
    
    //MARK: instantiating the Notification center...
    let notificationCenter = NotificationCenter.default
    
    //codes omitted...
}

Setting up an observer

Then we should start observing for a particular notification. We will use the following method: notificationCenter.addObserver(observer: Any, selector: Selector, name: NSNotification.Name?, object: Any?)

So let's add the following lines of code in viewDidLoad() method:

Here what we are doing is:

  • Setting the observer to self. This means this screen is observing for a notification.

  • We need to add a selector method to handle the data we get back as part of the notification. Here, we define notificationReceivedForTextChanged() method to handle the notification. Inside that method, you can see that we are setting the labelReceivedText's text to the received object.

  • We also need to give an identifier to the notification using the name parameter. We set the identifier as "textFromSecondScreen." It means I am just observing a notification of the name: "textFromSecondScreen."

  • The object parameter is nil. It means the first screen will not send any object; it will just listen.

Here is the entire code of the ViewController.swift:

Now, our first screen will listen to any notification named "textFromSecondScreen" and deal with it in notificationReceivedForTextChanged() method.

Last updated

Was this helpful?