Hi Friends today we will learn how to pass data between controllers using NSNotificationCenter in Swift. Earlier we learned how to pass the data between controllers using Delegate. (here)

 

Steps:

  1. Create a new Xcode project (lets Say NotificationSwift2)
  2. Now  create a new cococaClass and name it as (SecondViewController).
  3. Now go to StoryBoard and take a button in ViewController. Make a push connection to SecondViewController.

 

screen-shot-2016-10-15-at-1-25-49-pm

 

  1.  Now go to SecondViewController and take a button here also. And make IBoutlet Connection for this.

Screen Shot 2016-10-15 at 1.26.07 PM.png

  1. Now embed Navigation Controller in ViewController. Click on ViewController and then go to Editor – Embed In- Navigation Controller.

Screen Shot 2016-10-15 at 1.26.31 PM.png

  1. Your StoryBoard will look something like this.

Screen Shot 2016-10-15 at 1.27.03 PM.png

 

 

  1. Now its time  to code. Go to ViewController viewDidLoad and add a nsnotificationcenter observer and a method to listen the notification.

import UIKit

class ViewController: UIViewController {

  let notificationIdentifier: String = “NotificationIdentifier”

    override func viewDidLoad() {

        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.methodOfReceivedNotification(_:)), name:“NotificationIdentifier”, object: nil)

        // Do any additional setup after loading the view, typically from a nib.

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        // Dispose of any resources that can be recreated.

    }

    

    func methodOfReceivedNotification(notification : NSNotification) {

        let message = notification.object

        print(message)

        print(“I heard the notification!”)

    }

}

8. Now go to SecondViewController and in the Button Action we will write postNotification.

import UIKit

class SecondViewController: UIViewController {

    let notificationIdentifier: String = “NotificationIdentifier”

    override func viewDidLoad() {

        super.viewDidLoad()

        

       // Do any additional setup after loading the view.

    }

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

        

        // Dispose of any resources that can be recreated.

    }

    

    @IBAction func buttonAction(sender: AnyObject) {

        let message = “passingdata”

        

    NSNotificationCenter.defaultCenter().postNotificationName(notificationIdentifier, object: message)

        

        

    }

9. Now run the code. When You go to SecondViewController and click the Button. Method in ViewController will get called.And the message will also be passed.

You can download the whole project from here.

Please do share Your reviews.

Enjoy Coding 🙂

Advertisements