Swift didReceiveRemoteNotification userInfo can

2019-08-15 09:35发布

问题:

I use push notification, and have this func:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {
    if let msg = userInfo["msg"] as? NSObject {
        println(msg)
    }
    GCMService.sharedInstance().appDidReceiveMessage(userInfo);
    NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
        userInfo: userInfo)
}

this prints me:

{"model":"que","data":{"id":101,"vehicle":{"license_plate":"test","taxi":{"id":1,"logo":"/media/logos/mega_CxRn739.png.75x75_q85_crop.png","name":"Mega","city":"Novi Pazar","country":"Srbija"},"label":"A01"}}}

// prettify:
{
    "model": "que",
    "data": {
        "id": 101,
        "vehicle": {
            "license_plate": "test",
            "taxi": {
                "id": 1,
                "logo": "/media/logos/mega_CxRn739.png.75x75_q85_crop.png",
                "name": "Mega",
                "city": "Novi Pazar",
                "country": "Srbija"
            },
            "label": "A01"
        }
    }
}

Now when i use:

if let msg = userInfo["msg"] as? NSObject {
    println(msg["model"])
    println(msg["data"])
}

i can't build:

'NSObject' does not have a member named 'subscript'

How can i get this to work? I need to get all propertise after this, but can't do first step.

Image:

FIX:

if let msg = userInfo["msg"] as? String {
    if let data = msg.dataUsingEncoding(NSUTF8StringEncoding) {
        if let jsonObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(), error: nil) {
            var data = JSON(jsonObject!)
            println(data["data"])
        }
    }
}

If anyone have suggestion on this fix, tell me.. Thanks.

回答1:

if let msg = userInfo["msg"] as? String {
    if let data = msg.dataUsingEncoding(NSUTF8StringEncoding) {
        if let jsonObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(), error: nil) {
            var data = JSON(jsonObject!)
            println(data["data"])
        }
    }
}

If anyone have suggestion on this fix, tell me.. Thanks.



回答2:

the relevant objects in the payload are dictionaries, so cast the value of msg to something more specific

if let msg = userInfo["msg"] as? [String:AnyObject] {
    println(msg["model"])
    println(msg["data"])
}

Edit:

It could be that the object of msg is just a JSON string. Try this:

if let msg = userInfo["msg"] as? String {
   println("yeah, it's a string")
   if let data = msg.dataUsingEncoding(NSUTF8StringEncoding) {
      if let jsonObject: AnyObject? = NSJSONSerialization.JSONObjectWithData(data, options: NSJSONReadingOptions(), error: nil) {
        println(jsonObject["model"])
        println(jsonObject["data"])
      }
   }
}