Swift读取远程通知的userInfo [英] Swift read userInfo of remote notification
问题描述
当我收到这样的远程通知时,我实现了一个打开AlertView的函数:
I implemented a function to open an AlertView when I receive a remote notification like this:
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总是为零。
But NotificationMessage is always nil.
我的json有效载荷如下所示:
My json payload looks like this:
{"aps":{"alert":"Testmessage","badge":"1"}}
我正在使用Xcode 6,Swift和我正在为iOS8开发。
我现在搜索了几个小时,但没有找到任何有用的信息。
通知工作完美..如果我点击它,将打开alertview。
我的问题是,我无法从userInfo中获取数据。
I am using Xcode 6, Swift and I am developing for iOS8. I searched hours now, but didn't find any useful information. The Notifications works perfectly.. and if I click it, the alertview opens. My problem is, that I am not able to get the data out of userInfo.
推荐答案
根级项目 userInfo
字典是aps
,而不是alert
。
The root level item of the userInfo
dictionary is "aps"
, not "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
}
}
参见推送通知文档
这篇关于Swift读取远程通知的userInfo的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!