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

标签 ios swift2 google-cloud-messaging

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

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

我找不到如何获取警报正文和警报标题,我该怎么做?

最佳答案

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

关于ios - GCM iOS 无法转换收到的消息对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37460489/

相关文章:

ios - 如何在 iOS 设备上查看网络流量?

ios - UITableView 仅反弹底部边缘

ios - 使用 MapKit 时在创建时设置 MKPointAnnotation 的标题

swift 2/ cocoa : Good practice for large item collections and their impending UI updates

iphone - 如何更改Application Delegate 类?

xcode - Swift 2.0/Xcode 7B5 - 只有放入某个文件中才能找到类

swift - 如何在 Swift 函数的 return 语句之后运行代码?

android - 解析 onPushOpen 从未调用过

javascript - GCM 数据返回 null

php - 在后台 iOS GCM 中未收到推送通知