Search code examples
iosswiftnsnotificationcenternsnotification

Passing data between View Controllers with NSNotificationCenter


everyone. I wrote this code to pass data between VCs but I'm not sure why it's not working.

Here's the code in ViewController1:-

import UIKit
import Foundation

let foodDict: [String:String] = [
    "Orange": "Fruit",
    "Carrot": "Vegetable",
    "Pear": "Fruit",
    "Spinach": "Vegetable"
]

class ViewController1: UIViewController {

     override func viewDidLoad() {
         super.viewDidLoad()

         NSNotificationCenter.defaultCenter().postNotificationName("SEND_STRING", object: nil, userInfo: foodDict)

     }
 }

In ViewController2:-

import UIKit
import Foundation

class ViewController2: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        NSNotificationCenter.defaultCenter().addObserver(self, selector: "printStringDict:", name: "SEND_STRING", object: nil)
    }

    func printStringDict(notification: NSNotification) {

        print("Got the notification...")
        let foodDictFromVC1 = notification.userInfo as! [String:String]
        print(foodDictFromVC1)
    }

}

VC2 doesn't get the dictionary (since nothing prints). Can someone help? Thanks in advance.


Solution

  • So problem is that you post notification but your VC2 is not initialised yet so no-one can get this post that you have in view did load in VC1. It is better to use prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) function to communicate between two ViewControllers connected with segue for e.g.:

    import UIKit
    import Foundation
    
    
    
    class ViewController1: UIViewController {
    
        let foodDict: [String:String] = [
            "Orange": "Fruit",
            "Carrot": "Vegetable",
            "Pear": "Fruit",
            "Spinach": "Vegetable"
        ]
        override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
            if segue.identifier == "segueIdentifierSetInStoryboard" {
                if let destinationVC = segue.destinationViewController as? ViewController2{
                    destinationVC.printStringDict(foodDict)
                }
            }
        }
    }
    
    class ViewController2: UIViewController {       
        func printStringDict(fooDict:[String:String]) {
            print(fooDict)
        }
    }