gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 11:41:48 27 4
gpt4 key购买 nike

我使用 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)
}

如上所示,我可以毫无问题地获取data<内的titlemessagetimestamp的值 json。

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

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

最佳答案

像这样访问帖子 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")
}
}

关于json - 如何在 jsonObject swift 4 中获取 jsonObject 的值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49221334/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com