Alan Jay
Alan Jay

Reputation: 151

Google Firebase Messaging - parsing push notifications in Swift 3

I have been playing (successfully) with the Google Firebase Messaging system. I can send messages to my iPhone and subscribe / unsubscribe to groups / topics and now I want to manage and process the push notifications when they arrive at the phone.

   // Receive displayed notifications for iOS 10 devices.
func userNotificationCenter(_ center: UNUserNotificationCenter,
                            willPresent notification: UNNotification,
                            withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    let userInfo = notification.request.content.userInfo
    // Print message ID.
    if let messageID = userInfo[gcmMessageIDKey] {
        print("1 Message ID: \(messageID)")
    }

    // Print full message.
    print(userInfo)

    // Change this to your preferred presentation option
    completionHandler([])
}

This is the default code from google and I it works fine when a Push Notification arrives the app sees and prints:


    1 Message ID: 0:1007%4xxxxxxxxxa
    [AnyHashable("gcm.message_id"): 0:1007%4xxxxxa, AnyHashable("aps"): {
        alert =     {
            body = "Breaking News: ";
            title = "The latest update";
        };
        category = "http://amp.sportsmole.co.uk/football/";
    }]

However when I try to use the various Swift 3 JSON handling tools I end up with errors.

for example if I try:

 let data = userInfo[gcmMessageIDKey]
    let json = try? JSONSerialization.jsonObject(with: data, options: [])

I get an error that the jsonObject with argument type isn't what I needed.

Any insights?

Upvotes: 1

Views: 2142

Answers (1)

Alan Jay
Alan Jay

Reputation: 151

After some playing this seems to work:

    // Print full message.
    print("%@", userInfo)
    var body = ""
    var title = ""
    var msgURL = ""
    print("==============")

    guard let aps = userInfo["aps"] as? [String : AnyObject] else {
        print("Error parsing aps")
        return
    }
    print(aps)

    if let alert = aps["alert"] as? String {
        body = alert
    } else if let alert = aps["alert"] as? [String : String] {
        body = alert["body"]!
        title = alert["title"]!
    }

    if let alert1 = aps["category"] as? String {
        msgURL = alert1
    } 

    print(body)
    print(title)
    print(msgURL)

    //

Not sure if this is so obvious that I should have known it or if its just not something that is well documented.

Upvotes: 5

Related Questions