AnyHashable:当通过推送通知接收时,Any 不会迅速转换为字典 [英] AnyHashable:Any doesn't convert to dictionary in swift when receives through push notification

查看:32
本文介绍了AnyHashable:当通过推送通知接收时,Any 不会迅速转换为字典的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

  func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        startSavingNotification(userInfo: userInfo)
        completionHandler(UIBackgroundFetchResult.newData)
        //TODO: TEST
        //showTestPushAlert(userInfo: userInfo)
    }
    //Fire Test notification
    func startSavingNotification(userInfo:[AnyHashable : Any]) {
        //Fetch Payload Dict
        if let payloadDict = userInfo["payload"] as? Dictionary<String,Any> {
            savePushNotification(payloadDict: payloadDict)
        }
    }

func showTestPushAlert(userInfo:[AnyHashable : Any]) {
    let alert = UIAlertController(title:"", message: "\(userInfo)", preferredStyle: .alert)
    let cancelButton = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
    alert.addAction(cancelButton)
    UIApplication.topViewController()?.present(alert, animated: true, completion: nil)
}

当我尝试在警报中显示数据时,此用户信息如下所示:

When i try to show data in alert then this userinfo looks like this way :

如果条件为假,请在上面的行中做一些错误的事情:??if let payloadDict = userInfo["payload"] as?字典{savePushNotification(payloadDict: payloadDict)

Here above line if condition is getting false , do something wrong here :?? if let payloadDict = userInfo["payload"] as? Dictionary { savePushNotification(payloadDict: payloadDict) }

推荐答案

   //This method will parse push notification userinfo data
    func parseNotification(userInfo: [AnyHashable: Any]) {
        print(">>>parseNotificationCalled ")
        if let notification = userInfo["payload"] as? String,
            let jsonData = notification.data(using: .utf8),
            let dict = try? JSONSerialization.jsonObject(with: jsonData, options: .allowFragments) as? NSDictionary {
            //This is the point where we need to save push notification
            savePushNotification(payloadDict: dict ?? [:])
            print("APS PAYLOAD DICTIONARY \(dict)")
        }

就我而言,有效载荷字典采用字符串格式.解决了.​​

As in my case payload dictionary coming in string format. Solved.

这篇关于AnyHashable:当通过推送通知接收时,Any 不会迅速转换为字典的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆