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。 我现在搜查了几个小时,但没有find任何有用的信息。 通知完美地工作..如果我点击它,alertview打开。 我的问题是,我无法从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 } }
请参阅推送通知文档
对于我来说,当我从Accengage发送消息时,下面的代码工作 –
private func extractMessage(fromPushNotificationUserInfo userInfo:[NSObject: AnyObject]) -> String? { var message: String? if let aps = userInfo["aps"] as? NSDictionary { if let alert = aps["alert"] as? NSDictionary { if let alertMessage = alert["body"] as? String { message = alertMessage } } } return message }
与Craing Stanford的答案唯一的区别是我用来从alert
实例中提取消息的key
是不同的body
。 见下面更清晰 –
if let alertMessage = alert["message"] as? NSString
VS
if let alertMessage = alert["body"] as? String