Search code examples
iospush-notificationswift3apple-push-notificationsios10

How to get data from push notification response Swift 3/iOS


I am using the following library to generate push notifications.

https://github.com/edamov/pushok

I got the push notifications working but I don't know how to extract the response in Swift 3.

Here is what I have.

// Push notification received
    func application(_ application: UIApplication, didReceiveRemoteNotification data: [AnyHashable : Any]) {
        // Print notification payload data
        print("Push notification received: \(data)")

        let aps = data[AnyHashable("aps")]!

        print(aps)
    }

I can create the push notifications and the console message works but prints out this...

Push notification received: [AnyHashable("samplekey"): samplevalue, AnyHashable("aps"): {
    alert =     {
        body = hey;
        title = "Hello!";
    };
    sound = default;
}]
{
    alert =     {
        body = hey;
        title = "Hello!";
    };
    sound = default;
}

So my question is how do I access the data inside of alert for the 'body' and 'title'?

I tried accessing the variables but I keep getting errors because I'm not sure how I'm supposed to access it and could not find any documentation on this subject in any tutorials.


Solution

  • I think this is a safer way to do the way Joseph found.

    guard
        let aps = data[AnyHashable("aps")] as? NSDictionary,
        let alert = aps["alert"] as? NSDictionary,
        let body = alert["body"] as? String,
        let title = alert["title"] as? String
        else {
            // handle any error here
            return
        }
    
    print("Title: \(title) \nBody:\(body)")