【问题标题】:How to access the value of an incoming push notification如何访问传入推送通知的值
【发布时间】:2019-08-24 03:43:54
【问题描述】:

如何访问传入推送通知的标题?

    func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo

    // With swizzling disabled you must let Messaging know about the message, for Analytics
    // Messaging.messaging().appDidReceiveMessage(userInfo)

    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("Message ID: \(messageID)")
        self.numberOfNotifications += 1
    }

    // Print full message.
    print("Message: ", userInfo)

    //completionHandler([])

    // Change this to your preferred presentation option
    let data = userInfo.values as []//I would like to access the data here...

    completionHandler([.alert, .sound])
}

在上面我收到一条通知,我想检查特定文本的标题。如何以字符串形式访问测试来执行此操作?

【问题讨论】:

    标签: ios swift push-notification notifications


    【解决方案1】:

    标题键将在 aps["alert"] 字典中。 典型的推送通知消息如下所示

    {
        "aps" : {
            "alert" : {
                "title" : "Sample Title",
                "body" : "Hello World"
            },
            "badge" : 5
        }
    }
    

    消息可以这样访问-

    guard let aps = userInfo["aps"] as? [String: AnyObject],
        let alert = aps["alert"] as? [String:Any],
        let body = alert["body"] as? String,
        let title = alert["title"] as? String
    else {
      // handle any error here
      return
    }
    

    有关更多信息,您可以查看Apple 提供的文档。

    【讨论】:

    • 我试过了,尽管有通知,它总是运行 else 块
    • 让 aps = userInfo["aps"] 得到 nil
    • 请更新代码,以便我们可以看到您是如何访问 aps 数组的。也分享一个aps数组的样本。
    【解决方案2】:

    我用这个解决了我的问题:

            let data = userInfo["aps"] as? [String: AnyObject]
        if let alert = data?["alert"] as? [String: AnyObject] {
            completionHandler([])
        } else {
            completionHandler([.alert, .sound])
        }
    

    【讨论】:

      猜你喜欢
      • 2023-03-24
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多