How to get userInfo JSON Value inside didReceiveRemoteNotification

前端 未结 2 1097
北荒
北荒 2021-01-12 17:41
func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject])
{
        PFPush.handlePush(userInfo)

        if applica         


        
相关标签:
2条回答
  • 2021-01-12 18:13

    As mentioned in the comments, there is no key test in the APNS payload.
    If the value for key message is guaranteed to be sent always you can easily unwrap the value

    let msg = userInfo["message"] as! String
    print(msg)
    

    otherwise use optional binding

    if let msg = userInfo["message"] as? String {
        print(msg)
    }
    

    To get the alert dictionary from the aps key and print for example the body string use

    if let aps = userInfo["aps"] as? [String:Any],
       let alertDict = aps["alert"] as? [String:String] {
        print("body :", alertDict["body"]!)
    }
    
    0 讨论(0)
  • 2021-01-12 18:21

    I use APNs Provider and json payload as below

    {
      "aps" : {
        "alert" : {
          "title" : "I am title",
          "body" : "message body."
        },
      "sound" : "default",
      "badge" : 1
      }
    }
    

    Due to the provider originates it as a JSON-defined dictionary that iOS converts to an NSDictionary object, without subscript like Dictionary, but can use value(forKey:)

    Reference from here

    This's my way for Swift 4

    func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
        guard application.applicationState == .active else { return }
        guard let alertDict = ((userInfo["aps"] as? NSDictionary)?.value(forKey: "alert")) as? NSDictionary,
            let title = alertDict["title"] as? String,
            let body = alertDict["body"] as? String
            else { return }
        let alertController = UIAlertController(title: title, message: body, preferredStyle: .alert)
        let okAct = UIAlertAction(title: "Ok", style: .default, handler: nil)
        alertController.addAction(okAct)
        self.window?.rootViewController?.present(alertController, animated: true, completion: nil)
        completionHandler(UIBackgroundFetchResult.noData)
    }
    
    0 讨论(0)
提交回复
热议问题