how to pass multiple values with a notification in swift

前端 未结 6 1743
广开言路
广开言路 2020-11-27 05:06

How to send a number and a String through a notification ...

let mynumber=1;
let mytext=\"mytext\";
NSNotificationCenter.defaultCenter().postNotificationName         


        
6条回答
  •  野趣味
    野趣味 (楼主)
    2020-11-27 05:37

    Swift 4.0

    First create a dictionary for multiple values.

    let name = "Abhi"
    let age = 21
    let email = "abhi@xyz.com"
    let myDict = [ "name": name, "age":age, "email":email]
    // post myDict
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "post"), object: nil, userInfo: myDict)
    

    Add observer in other ViewController

    NotificationCenter.default.addObserver(self, selector: #selector(doThisWhenNotify(notification:)), name: NSNotification.Name(rawValue: "post"), object: nil)
    
    func doThisWhenNotify(notification : NSNotification) {
        let info = notification.userInfo
        print("name : ",info["name"])
        print("age : ",info["age"])
        print("email : ",info["email"])
    
    }
    

提交回复
热议问题