如何解析应用程序中的userInfo字典(应用程序:UIApplication,didReceiveRemoteNotification userInfo:[NSObject:AnyObject])

时间:2016-01-09 12:57:03

标签: ios json swift

我是Swift的新手,请原谅我,如果这是一个愚蠢的问题。这是我推送到我的应用程序的JSON:

{
  "aps": {
    "alert": "Jack Terrance needs your help",
    "badge": 1,
    "sound": "default",
    "data": {
      "from": "Jack Terrance",
      "from_num": "+1234567890"
    }
  }
}

我设法接收JSON,但我无法弄清楚如何解析它:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]) {

        let message : String = userInfo.map({$0["aps"]!["alert"] as String})

        UIAlertView(title: "Notification", message: message!, delegate: nil, cancelButtonTitle: "OK").show();

    }

我正在寻找的东西相当于Objective-C中的valueForKeyPath

1 个答案:

答案 0 :(得分:0)

//请尝试下面。希望这对你有用。

if let aps = userInfo["aps"] as? NSDictionary {

    if let alert = aps["alert"] as? NSString {
       //Do stuff
    }else if let badge = alert["badge"] as? NSString {
       //Do stuff
    }else if let sound = aps["sound"] as? NSString {
       //Do stuff
    }

    if let data = aps["data"] as? NSDictionary {

        if let alert = data["from"] as? NSString {
            //Do stuff
        }else if let from_num = data["from_num"] as? NSString {
           //Do stuff
        }
    }
}