我想从firebase推送通知中解析数据,并且数据与“ aps”一起出现,我在解析时遇到了困难。这是我在推送中接收的数据。我想解析“ PnType”,“提取”。
[
AnyHashable("CustomData"):
{
"PnType":"PnNewJob",
"PnResult":
{
"JobId":1743,
"JobRef":"CAS4491055071",
"Pickup":"Basil And Bean Co, phase-7, Mohali, Punjab, India",
"DropOff":"Elante Mall, Chandigarh, Chandigarh, India",
"Cost":9.00,
"TotalMiles":4.93
}
},
AnyHashable("google.c.a.e"): 1,
AnyHashable("gcm.message_id"): 0:1555505650971833%277c5a32277c5a32,
AnyHashable("aps"):
{
alert =
{
body = "Hellodrive Notification";
title = "HelloDrive Notification";
};
badge = 1;
"content-available" = 1;
}
]
我尝试像
那样解析let customData = userInfo["CustomData"] as? [AnyHashable: Any]
我每次都变得零。
答案 0 :(得分:1)
我尝试使用NWPusher应用推送通知。
推送了JSON:
{
"CustomData": {
"PnType": "PnNewJob",
"PnResult": {
"JobId": 1743,
"JobRef": "CAS4491055071",
"Pickup": "Basil And Bean Co, phase-7, Mohali, Punjab, India",
"DropOff": "Elante Mall, Chandigarh, Chandigarh, India",
"Cost": 9,
"TotalMiles": 4.93
}
},
"google.c.a.e": 1,
"gcm.message_id": "0:1555505650971833%277c5a32277c5a32",
"aps": {
"alert": {
"body": "Hellodrive Notification",
"title": "HelloDrive Notification"
},
"badge": 1,
"content-available": 1
}
}
以下是didReceiveRemoteNotification
[[AnyHashable("aps"): {
alert = {
body = "Hellodrive Notification";
title = "HelloDrive Notification";
};
badge = 1;
"content-available" = 1;
}, AnyHashable("google.c.a.e"): 1, AnyHashable("CustomData"): {
PnResult = {
Cost = 9;
DropOff = "Elante Mall, Chandigarh, Chandigarh, India";
JobId = 1743;
JobRef = CAS4491055071;
Pickup = "Basil And Bean Co, phase-7, Mohali, Punjab, India";
TotalMiles = "4.93";
};
PnType = PnNewJob;
}, AnyHashable("gcm.message_id"): 0:1555505650971833%277c5a32277c5a32]]
现在,我使用userInfo
方法中的以下代码从didReceiveRemoteNotification
中检索了值。它工作得很好。
if let customData = userInfo["CustomData"] as? [AnyHashable: Any] {
if let pnType = customData["PnType"] as? String {
print("PNType: \(pnType)")
}
if let pnResult = customData["PnResult"] as? [AnyHashable: Any] {
if let pickup = pnResult["Pickup"] as? String {
print("Pickup: \(pickup)")
}
}
}
输出
PNType: PnNewJob
Pickup: Basil And Bean Co, phase-7, Mohali, Punjab, India
答案 1 :(得分:0)
首先将userInfo
转换为更具体的[String:Any]
,然后提取值
if let userInfo = userInfo as? [String:Any],
let customData = userInfo["CustomData"] as? [String:Any] {
let pnType = customData["PnType"] as? String
print(pnType ?? "n/a")
if let pnResult = customData["PnResult"] as? [String:Any],
let pickup = pnResult["Pickup"] as? String {
print(pickup)
}
}