简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM