如何在jsonObject swift 4中获取jsonObject的值?

时间:2018-03-11 14:53:40

标签: json swift dictionary

我使用FCM向我的iOS应用程序发送推送通知。当用户点击通知托盘时,数据句柄由以下功能处理:

func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        print(userInfo['data'])
}

userInfo[AnyHashable:Any]类型。我成功获取了userInfo['data']的数据。所以这里是userInfo['data']的数据结构:

'{"data":
   {
    "title":"My app",
    "message":"The message here",
    "payload":{
        "post_id":"602"
        },
    "timestamp":"2018-03-10 14:12:08"
    }
 }'

以下是我尝试的方式:

 if let dataString = userInfo["data"] as? String {

        let data = dataString.data(using: .utf8)!

        do {
            if let json = try JSONSerialization.jsonObject(with: data, options : .allowFragments) as? [String : Any]
            {
                let message = json["message"] as? String ?? "No message here"
                let title = json["title"] as String ?? ""

                //here is the problem..I have no idea to do it here
                let payload = json["payload"] as? [String : Int] ?? [:]

                for element in payload {
                    if let postId = element["post_id"] {
                        //print("postId = \(postId)")
                    }


                }
            } else {
                print("bad json")
            }
    } catch let error as NSError {
        print(error)
    }

如上所示,我在title json中获得messagetimestampdata的价值没有问题。

但我必须知道如何获得位于post_id数组内的payload的值。

那么在这种情况下,如何从上面的post_id json获取data的值?感谢。

1 个答案:

答案 0 :(得分:0)

像这样访问帖子ID

   func userNotificationCenter(_ center: UNUserNotificationCenter,
                                didReceive response: UNNotificationResponse,
                                withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        if let data = userInfo["data"] as? [String: Any],
            let payload = data["payload"] as? [String: Any],
            let postId = payload["post_id"] as? String{
            print("post id \(postId)")
        }else{
            print("there is no post id inside the payload")
        }
    }