AnyHashable:Any doesn't convert to dictionary in swift when receives through push notification

匿名 (未验证) 提交于 2019-12-03 01:36:02

问题:

  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 :

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

回答1:

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



易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!