从 Apple 推送通知中解析数据
Posted
技术标签:
【中文标题】从 Apple 推送通知中解析数据【英文标题】:Parse Data from Apple Push Notification 【发布时间】:2018-04-15 17:15:03 【问题描述】:我通过 Firebase 发送推送通知,当用户执行操作时,有一个 php 脚本向关联的 FCM 令牌发送推送。正在接收推送通知,但我正在尝试从“gcm.notification.payload”键中获取信息。我尝试将 userInfo 转换为 Dictionary、NSDictionary、[String:Any]、JSON,但没有任何效果。当我尝试说payload [“type”].string时,该值为nil。这是我最接近能够从有效负载字典中获取某些内容的方法,其中通知是收到的 UNNotification:
let userInfo = notification.request.content.userInfo
let json = JSON(notification.request.content.userInfo)
guard let gcmNotificationPayload = json["gcm.notification.payload"].string else return
let payload = JSON(gcmNotificationPayload)
print("json \(json)")
print("payload \(payload)")
print("\(notification.request.content.userInfo)")
控制台输出:
json
"gcm.message_id" : "0:1523811750249807%3990eb5d3990eb5d",
"aps" :
"sound" : "default",
"badge" : 1,
"alert" :
"body" : "Tap to Open Herds List",
"title" : "test4 test has added you to a herd!"
,
"gcm.notification.payload" : "\"image\":\"https:\\\/\\\/www.test.com\\\/images\\\/users\\\/417\\\/5acd085c97c3a.jpg\",\"type\":\"6\",\"title\":\"test4 test has added you to a herd!\",\"message\":\"Tap to Open Herds List\""
payload "image":"https:\/\/www.test.com\/images\/users\/417\/5acd085c97c3a.jpg","type":"6","title":"test4 test has added you to a herd!","message":"Tap to Open Herds List"
[AnyHashable("gcm.message_id"): 0:1523811750249807%3990eb5d3990eb5d, AnyHashable("aps"):
alert =
body = "Tap to Open Herds List";
title = "test4 test has added you to a herd!";
;
badge = 1;
sound = default;
, AnyHashable("gcm.notification.payload"): "image":"https:\/\/www.test.com\/images\/users\/417\/5acd085c97c3a.jpg","type":"6","title":"test4 test has added you to a herd!","message":"Tap to Open Herds List"]
【问题讨论】:
【参考方案1】:将 let 有效负载行更改为此解决了问题,这是使用 SwiftyJSON 进行记录:
let payload = JSON.init(parseJSON: gcmNotificationPayload)
【讨论】:
无论如何,我建议您查看Codable
protocol,它使处理JSON
变得容易得多。以上是关于从 Apple 推送通知中解析数据的主要内容,如果未能解决你的问题,请参考以下文章