Google Firebase Messaging - 在 Swift 3 中解析推送通知



我一直在玩(成功(Google Firebase消息系统。 我可以向我的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([])
}

这是来自谷歌的默认代码,我当推送通知到达应用程序看到并打印时,它工作正常:


    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/";
    }]

但是,当我尝试使用各种 Swift 3 JSON 处理工具时,我最终会遇到错误。

例如,如果我尝试:

 let data = userInfo[gcmMessageIDKey]
    let json = try? JSONSerialization.jsonObject(with: data, options: [])

我收到一个错误,指出参数类型的 jsonObject 不是我需要的。

有什么见解吗?

玩了一会儿后,这似乎有效:

    // 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)
    //

不确定这是否如此明显以至于我应该知道它,或者它只是没有很好的记录。

相关内容

最新更新