GCM iOS无法转换收到的消息对象

时间:2016-05-26 12:10:58

标签: ios swift2 google-cloud-messaging

我正在使用GCM for iOS,我收到了我推送的消息,但消息看起来像这个对象:

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

这是我收到消息时调用的整个函数:

 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]
    }

我没有找到如何获取警报正文和提醒标题我该怎么做?

1 个答案:

答案 0 :(得分:1)

userInfo是[NSObject:AnyObject]类型的字典。要访问这些值,请使用下标。

“aps”键包含一个包含字典的字典,例如,你可以这样做:

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