Search code examples
iosswiftnotificationsfirebase-notifications

Fetching data from Custom Payload Swift


I'm using custom payload for notification & I get notification but I'm unable to fetch from Key["data"]. Here is my Payload code

{
    "Simulator Target Bundle": "com.xyz.zyxapp",
   "aps" : {
        "alert" : "It's a notification with custom payload!",
        "badge" : 1,
        "content-available" : 0         
    },
    "data" :{
        "title" : "Game Request",
        "body" : "Bob wants to play poker",
        "action-loc-key" : "PLAY"
    },
  }  

I'm trying to access data from didreceive method

 func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
  {
     print(response.notification.request.content.body)
}

result is: It's a notification with custom payload! If anyone can help me with this will be appreciated. Thanks in advance Regards.


Solution

  • Parse custom data in notification's userInfo property instead of body. userInfo is a dictionary of custom information associated with the notification.

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
        let userInfo = response.notification.request.content.userInfo
        if let data = userInfo["data"] as? [String: Any] {
            //
            //Do your parsing here..
        }
    }