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

Ala*_*Jay 1 apple-push-notifications firebase swift swift3

我一直在(成功地)使用 Google Firebase Messaging 系统。我可以向我的 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([])
}
Run Code Online (Sandbox Code Playgroud)

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


    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/";
    }]
Run Code Online (Sandbox Code Playgroud)

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

例如,如果我尝试:

 let data = userInfo[gcmMessageIDKey]
    let json = try? JSONSerialization.jsonObject(with: data, options: [])
Run Code Online (Sandbox Code Playgroud)

我收到一个错误,表明带有参数类型的 jsonObject 不是我需要的。

有什么见解吗?

Ala*_*Jay 5

经过一番玩后,这似乎有效:

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

    //
Run Code Online (Sandbox Code Playgroud)

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