[英]Google Firebase Messaging - parsing push notifications in Swift 3
I have been playing (successfully) with the Google Firebase Messaging system. 我一直在(成功)使用Google Firebase Messaging系统。 I can send messages to my iPhone and subscribe / unsubscribe to groups / topics and now I want to manage and process the push notifications when they arrive at the phone.
我可以将消息发送到我的iPhone并订阅/取消订阅组/主题,现在我想在推送通知到达电话时对其进行管理和处理。
// Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
willPresent notification: UNNotification,
withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
let userInfo = notification.request.content.userInfo
// Print message ID.
if let messageID = userInfo[gcmMessageIDKey] {
print("1 Message ID: \(messageID)")
}
// Print full message.
print(userInfo)
// Change this to your preferred presentation option
completionHandler([])
}
This is the default code from google and I it works fine when a Push Notification arrives the app sees and prints: 这是Google的默认代码,当推送通知到达时,该应用可以看到并打印:
1 Message ID: 0:1007%4xxxxxxxxxa
[AnyHashable("gcm.message_id"): 0:1007%4xxxxxa, AnyHashable("aps"): {
alert = {
body = "Breaking News: ";
title = "The latest update";
};
category = "http://amp.sportsmole.co.uk/football/";
}]
However when I try to use the various Swift 3 JSON handling tools I end up with errors. 但是,当我尝试使用各种Swift 3 JSON处理工具时,都会遇到错误。
for example if I try: 例如,如果我尝试:
let data = userInfo[gcmMessageIDKey]
let json = try? JSONSerialization.jsonObject(with: data, options: [])
I get an error that the jsonObject with argument type isn't what I needed. 我收到一个错误,指出参数类型的jsonObject不是我所需要的。
Any insights? 有什么见解吗?
After some playing this seems to work: 经过一番打法,这似乎可行:
// Print full message.
print("%@", userInfo)
var body = ""
var title = ""
var msgURL = ""
print("==============")
guard let aps = userInfo["aps"] as? [String : AnyObject] else {
print("Error parsing aps")
return
}
print(aps)
if let alert = aps["alert"] as? String {
body = alert
} else if let alert = aps["alert"] as? [String : String] {
body = alert["body"]!
title = alert["title"]!
}
if let alert1 = aps["category"] as? String {
msgURL = alert1
}
print(body)
print(title)
print(msgURL)
//
Not sure if this is so obvious that I should have known it or if its just not something that is well documented. 不知道这是否如此明显以至于我应该知道它,还是只是没有充分记录的东西。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.