26

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=?????????
    }
mcfly soft
  • 11,289
  • 26
  • 98
  • 202

6 Answers6

35

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"]
}
Pfitz
  • 7,336
  • 4
  • 38
  • 51
  • Thanks it works, but I get the value "Optional(mytext)" for the text. Is this supposed to be and I have to remove the optional string or am I doing something wrong. – mcfly soft May 19 '15 at 14:53
  • @mcflysoft Have a look at this about Optionals: https://developer.apple.com/library/prerelease/ios/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html#//apple_ref/doc/uid/TP40014097-CH5-ID330 – Eric Aya May 19 '15 at 15:10
29

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": "abc@def.com"]
NotificationCenter.default.post(name: .refresh, object: object)
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
15

You can use the userInfo property of Notification:

NotificationCenter.default.post(name: Notification.Name("refresh"),
                                object: nil,
                                userInfo: ["number":yourNumber, "string":yourString])

and to retrieve:

func refreshList(notification: Notification){
    let receivednumber = notification.userInfo?["number"] as? Int ?? 0
    let receivedString = notification.userInfo?["string"] as? String ?? ""
}
Cristik
  • 30,989
  • 25
  • 91
  • 127
EagerMike
  • 2,032
  • 1
  • 24
  • 40
5

Actually there are a lot of way to do this. One of them is to pass an array of objects like :

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
}
Zell B.
  • 10,266
  • 3
  • 40
  • 49
3

Swift 4.0, I am passing single key:value, you can add multiple keys and values.

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

Adding Observer and Method definition. You also need to remove observer.

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 ?? "")
    }
Gurjinder Singh
  • 9,221
  • 1
  • 66
  • 58
3

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"])

}
Deep
  • 416
  • 6
  • 15