fandro fandro - 6 months ago 35
iOS Question

GCM iOS can't convert message object received

I m using GCM for iOS and I receive the message that I push but the message look like this object :

[aps: {
alert = {
body = "great match!";
title = "Portugal vs. Denmark";
};
}, gcm.message_id: 0:1464264430528872......]


Here is the entire function called when I receive a message :

func application( application: UIApplication,
didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
fetchCompletionHandler handler: (UIBackgroundFetchResult) -> Void) {
print("Notification received: \(userInfo)")
print(userInfo)
// This works only if the app started the GCM service
GCMService.sharedInstance().appDidReceiveMessage(userInfo);
// Handle the received message
// Invoke the completion handler passing the appropriate UIBackgroundFetchResult value
// [START_EXCLUDE]
NSNotificationCenter.defaultCenter().postNotificationName(messageKey, object: nil,
userInfo: userInfo)
handler(UIBackgroundFetchResult.NoData);
// [END_EXCLUDE]
}


I don't find how to get the alert body and alert title how can I do that ?

Answer

userInfo is a dictionary of type [NSObject : AnyObject]. To access the values, use subscripting.

The "aps" key contains a dictionary which contains a dictionary, so, for example, you could do:

if let aps = userInfo["aps"] as? [String:[String:String]],
        alert = aps["alert"],
        body = alert["body"],
        title = alert["title"] {
    print(title)
    print(body)
}
Comments