我在我的应用程序中实现推送通知。当有人向我发送消息时我收到了针对该消息的数据,我想对我收到的数据执行一些操作,但我无法获得值。这是我的代码。
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
guard let data = try? JSONSerialization.data(withJSONObject: remoteMessage.appData, options:.prettyPrinted),
let prettyPrinted = String(data: data, encoding: .utf8) else { return }
print("Received direct channel message:\n\(prettyPrinted)")
}
这是我的控制台输出。
Received data message: [AnyHashable("chat"): {"date":"1 second(s)
ago","img":"http:\/\/adforest-testapp.scriptsbundle.com\/wp-
content\/plugins\/adforest-rest-api\/images\/user.jpg","ad_id":"439","id":244,"text":"hi","type":"reply"},
AnyHashable("adId"): 439, AnyHashable("from"): 170168176816,
AnyHashable("title"): Honda Civic 2017 Type R, AnyHashable("message"):
hi, AnyHashable("senderId"): 47, AnyHashable("recieverId"): 1,
AnyHashable("topic"): chat, AnyHashable("type"): receive]
这是我的漂亮印花JSON。 收到直接频道消息:
{
"chat" : "{\"date\":\"1 second(s)
ago\",\"img\":\"http:\\\/\\\/adforest-testapp.scriptsbundle.com\\\/wp-
content\\\/plugins\\\/adforest-rest-api\\\/images\\\/user.jpg\",\"ad_id\":\"439\",\"id\":244,\"text\":\"hi\",\"type\":\"reply\"}",
"adId" : "439",
"from" : "170168176816",
"title" : "Honda Civic 2017 Type R",
"message" : "hi",
"senderId" : "47",
"recieverId" : "1",
"topic" : "chat",
"type" : "receive"
}
请指导我如何从中获取关键值并用于执行某些操作。
答案 0 :(得分:1)
你试过这个吗?
let chat = remoteMessage.appData[AnyHashable("chat")]
let adId = remoteMessage.appData[AnyHashable("adId")]
let from = remoteMessage.appData[AnyHashable("from")]
let title = remoteMessage.appData[AnyHashable("title")]
let message = remoteMessage.appData[AnyHashable("message")]
let topic = remoteMessage.appData[AnyHashable("topic")]
答案 1 :(得分:0)
试试这段代码
var json = Populate(NSJSONSerialization.JSONObjectWithData(data, options: nil, error: nil) as! NSDictionary)
var chat = json["chat"] as! Chat
var adId = json["adId"] as! String
var from = json["from"] as! String
var title = json["title"] as! String
var message = json["message"] as! String
var senderId = json["senderId"] as! String
var recieverId = json["recieverId"] as! String
var topic = json["topic"] as! String
var type = json["type"] as! String
答案 2 :(得分:-1)
func messaging(_ messaging: Messaging, didReceive remoteMessage: MessagingRemoteMessage) {
print("Received data message: \(remoteMessage.appData)")
guard let data = try? JSONSerialization.data(withJSONObject: remoteMessage.appData, options:.prettyPrinted),
let prettyPrinted = String(data: data, encoding: .utf8) else { return }
print("Received direct channel message:\n\(prettyPrinted)")
let chatDic = prettyPrinted["chat"] as Dictionary<String, Any>
let dataString = chatDic["date"] as String
let img = chatDic["img"] as String
let ad_id = chatDic["ad_id"] as String
let id = chatDic["id"] as Int
let text = chatDic["text"] as String
let type = chatDic["type"] as String
}