AnyHashable:Any doesn't convert to dictionary

2019-06-09 22:14发布

问题:

  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.



标签: ios swift4