Как передать несколько значений с уведомлением в swift

Как отправить номер и строку через уведомление...

let mynumber=1;
let mytext="mytext";
NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: ?????????????);

и получить значения в приемнике?

func refreshList(notification: NSNotification){
        let receivednumber=??????????
        let receivedString=?????????
    }

Ответы

Ответ 1

Вы можете обернуть их в NSArray или NSDictionary или пользовательский объект.

Например:

let mynumber=1;
let mytext="mytext";

let myDict = [ "number": mynumber, "text":mytext]

NSNotificationCenter.defaultCenter().postNotificationName("refresh", object:myDict);

func refreshList(notification: NSNotification){
    let dict = notification.object as! NSDictionary
    let receivednumber = dict["number"]
    let receivedString = dict["mytext"]
}

Ответ 2

Xcode 8.3.1 • Swift 3.1

extension Notification.Name {
    static let refresh = Notification.Name("refresh")
}

let object: [String: Any] = ["id": 1, "email": "[email protected]"]
NotificationCenter.default.post(name: .refresh, object: object)

NotificationCenter.default.addObserver(self, selector: #selector(refreshList), name: .refresh, object: nil)

// don't forget  vvv add an underscore before the view controller method parameter 
func refreshList(_ notification: Notification) {
    if let object = notification.object as? [String: Any] {
        if let id = object["id"] as? Int {
            print(id)
        }
        if let email = object["email"] as? String {
            print(email)
        }
    }
}

Ответ 3

Используйте userInfo

NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: nil, userInfo: ["number":yourNumber,
                              "string":yourString]

и получить:

func refreshList(notification: NSNotification){ 
    let userInfo = notification.userInfo as Dictionary
    let receivednumber = userInfo["number"]
    let receivedString = userInfo["string"]
}

Im не сильный на быстрых (непроверенных), но вы получаете идею.

Ответ 4

На самом деле есть много способов сделать это. Один из них - передать массив таких объектов, как:

let arrayObject : [AnyObject] = [mynumber,mytext]

NSNotificationCenter.defaultCenter().postNotificationName("refresh", object: arrayObject)

func refreshList(notification: NSNotification){

    let arrayObject =  notification.object as! [AnyObject]

    let receivednumber = arrayObject[0] as! Int
    let receivedString = arrayObject[1] as! String
}

Ответ 5

Swift 4.0, я передаю один ключ: значение, вы можете добавить несколько ключей и значений.

   NotificationCenter.default.post(name:NSNotification.Name(rawValue: "updateLocation"), object: ["location":"India"])

Добавление определения Observer и Method. Вам также необходимо удалить наблюдателя.

NotificationCenter.default.addObserver(self, selector: #selector(getDataUpdate), name: NSNotification.Name(rawValue: "updateLocation"), object: nil)

@objc func getDataUpdate(notification: Notification) {
        guard let object = notification.object as? [String:Any] else {
            return
        }
        let location = object["location"] as? String
        self.btnCityName.setTitle(location, for: .normal)

        print(notification.description)
        print(notification.object ?? "")
        print(notification.userInfo ?? "")
    }

Ответ 6

Swift 4.0

Сначала создайте словарь для нескольких значений.

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

Добавить наблюдателя в другой 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"])

}