Swift didReceiveRemoteNotification userInfo 无法获取值

Swift didReceiveRemoteNotification userInfo can't get value

我使用推送通知,并且有这个功能:

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

这打印我:

{"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"
        }
    }
}

现在当我使用:

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

我无法构建:

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

我怎样才能让它工作?之后我需要获得所有属性,但无法执行第一步。

图片:

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

如果有人对此修复有建议,请告诉我。谢谢。

有效负载中的相关对象是字典,因此将 msg 的值转换为更具体的内容

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

编辑:

可能 msg 的对象只是一个 JSON 字符串。 试试这个:

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

如果有人对此修复有建议,请告诉我。谢谢。