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

标签 swift firebase apple-push-notifications swift3

我一直在(成功地)使用 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)

    //

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

关于swift - Google Firebase Messaging - 在 Swift 3 中解析推送通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42873884/

相关文章:

php - 具有多个应用程序的APNS推送服务器

swift - 如何使用 DateComponentsFormatter 将日期显示为 "Today"或 "Yesterday"?

firebase - Unity Firebase 自动创建匿名帐户

android - 如何在应用程序自动注销时收到通知并在关闭时清理数据

javascript - 使用 push(data) Angularfire2 时处理错误

iphone - 使用推送通知在指定页面打开应用程序

iOS:有没有办法知道用户是否选择退出通知?

ios - 如何在 ibeacon 中使用唯一标识符?

ios - 从详细信息页面返回表格 View ,无需重新加载表格

Swift 从 'UIViewController?' 转换为不相关类型 'TableViewCell' 总是失败