Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass multiple values with a notification in swift

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

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

and receive the values in the receiver ?

func refreshList(notification: NSNotification){
        let receivednumber=??????????
        let receivedString=?????????
    }
like image 239
mcfly soft Avatar asked May 19 '15 14:05

mcfly soft


2 Answers

You could wrap them in an NSArray or a NSDictionary or a custom Object.

Eg:

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"]
}
like image 92
Pfitz Avatar answered Nov 15 '22 04:11

Pfitz


Swift 4 or later

Declare a notification name to be used

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

Add an observer for that name in your view controller viewDidLoad method and a selector to get the notification object

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

@objc 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)
        }
    }
}

Post your notification with your object:

let object: [String: Any] = ["id": 1, "email": "[email protected]"]
NotificationCenter.default.post(name: .refresh, object: object)
like image 37
Leo Dabus Avatar answered Nov 15 '22 04:11

Leo Dabus