我使用 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
json 中获取 title
、message
和 timestamp
的值没有问题。
但是我必须知道如何获取数组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")
}
}