ios - Swift读取远程通知的userInfo

当我收到这样的远程通知时,我实现了一个打开 AlertView 的功能:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject]){
        var notifiAlert = UIAlertView()
        var NotificationMessage : AnyObject? =  userInfo["alert"]
        notifiAlert.title = "TITLE"
        notifiAlert.message = NotificationMessage as? String
        notifiAlert.addButtonWithTitle("OK")
        notifiAlert.show()
}

但 NotificationMessage 始终为零。

我的 json 有效负载如下所示:

{"aps":{"alert":"Testmessage","badge":"1"}}

我正在使用 Xcode 6、Swift 并且正在为 iOS8 进行开发。 我现在搜索了几个小时,但没有找到任何有用的信息。 通知工作得很好..如果我点击它,警报 View 就会打开。 我的问题是,我无法从 userInfo 中获取数据。

最佳答案

userInfo 字典的根级项是"aps",而不是"alert"

尝试以下方法:

if let aps = userInfo["aps"] as? NSDictionary {
    if let alert = aps["alert"] as? NSDictionary {
        if let message = alert["message"] as? NSString {
           //Do stuff
        }
    } else if let alert = aps["alert"] as? NSString {
        //Do stuff
    }
}

见 Push Notification Documentation

https://stackoverflow.com/questions/28596295/

相关文章:

json - 如何从 nginx 生成 JSON 日志?

python - 在 Python 中将 JSON 转换为字符串

java - Retrofit2 安卓 : Expected BEGIN_ARRAY but was

php - 带有双引号的json解析错误

python - 不是 JSON 可序列化的

json - postman - 如何将全局变量传递到 JSON 正文

java - 在 Java 中将 JSON 转换为 XML

json - 将导入的 json 数据导入数据框

python - python中的 pretty-print json(pythonic方式)

java - 如何将 POJO 转换为 JSON,反之亦然?