【问题标题】:Google Firebase Messaging - parsing push notifications in Swift 3Google Firebase Messaging - 在 Swift 3 中解析推送通知
【发布时间】:2017-03-18 11:38:33
【问题描述】:

我一直在(成功地)使用 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 不是我需要的。

有什么见解吗?

【问题讨论】:

  • 玩了一段时间后,这似乎有效:

标签: swift firebase swift3 apple-push-notifications swift3.0.2


【解决方案1】:

玩了一段时间后,这似乎有效:

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

    //

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

【讨论】:

    猜你喜欢
    • 2017-10-10
    • 1970-01-01
    • 1970-01-01
    • 2017-02-05
    • 1970-01-01
    • 1970-01-01
    • 2022-12-14
    • 2017-01-05
    • 2016-06-24
    相关资源
    最近更新 更多