ios Swift 读取远程通知的 userInfo
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28596295/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift read userInfo of remote notification
提问by F3rret
I implemented a function to open an AlertView when I receive a remote notification like this:
当我收到这样的远程通知时,我实现了一个打开 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()
}
But NotificationMessage is always nil.
但是 NotificationMessage 始终为零。
My json payload looks like this:
我的 json 有效负载如下所示:
{"aps":{"alert":"Testmessage","badge":"1"}}
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.
我正在使用 Xcode 6、Swift 并且正在为 iOS8 进行开发。我现在搜索了几个小时,但没有找到任何有用的信息。通知工作完美......如果我点击它,警报视图会打开。我的问题是,我无法从 userInfo 中获取数据。
回答by Craig Stanford
The root level item of the userInfo
dictionary is "aps"
, not "alert"
.
userInfo
字典的根级别项目是"aps"
,不是"alert"
。
Try the following:
请尝试以下操作:
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
}
}
See Push Notification Documentation
请参阅推送通知文档
回答by Ming Chu
Method (Swift 4):
方法(Swift 4):
func extractUserInfo(userInfo: [AnyHashable : Any]) -> (title: String, body: String) {
var info = (title: "", body: "")
guard let aps = userInfo["aps"] as? [String: Any] else { return info }
guard let alert = aps["alert"] as? [String: Any] else { return info }
let title = alert["title"] as? String ?? ""
let body = alert["body"] as? String ?? ""
info = (title: title, body: body)
return info
}
Usage:
用法:
let info = self.extractUserInfo(userInfo: userInfo)
print(info.title)
print(info.body)
回答by BLC
For me, when I send the message from Accengage, the following code works -
对我来说,当我从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
}
The only difference from Craing Stanford's answer is the key
I used to extract message from alert
instance which is body
which is different. See below for more clearification -
与 Craing Stanford's answer 的唯一区别是key
I used to extract message from alert
instance which is body
which is different。请参阅下文了解更多信息 -
if let alertMessage = alert["message"] as? NSString
vs
对比
if let alertMessage = alert["body"] as? String
回答by jaiswal Rajan
Alert should be showing while the app is in active state. So check the state is active or not.
当应用程序处于活动状态时,应显示警报。因此,请检查状态是否处于活动状态。
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
if application.applicationState == .active {
if let aps = userInfo["aps"] as? NSDictionary {
if let alertMessage = aps["alert"] as? String {
let alert = UIAlertController(title: "Notification", message: alertMessage, preferredStyle: UIAlertControllerStyle.alert)
let action = UIAlertAction(title: "Ok", style: .default, handler: nil)
alert.addAction(action)
self.window?.rootViewController?.present(alert, animated: true, completion: nil)
}
}
}
completionHandler(.newData)
}
From this if a user need message then he can get alert message.
如果用户需要消息,那么他可以获得警报消息。
回答by Joshpy
I use APNs Provider and json payload as below
我使用 APNs Provider 和 json 负载如下
{
"aps" : {
"alert" : {
"title" : "I am title",
"body" : "message body."
},
"sound" : "default",
"badge" : 1
}
}
Due to the provider originates it as a JSON-defined dictionary that iOS converts to an NSDictionary
object, without subscript like Dictionary
, but can use value(forKey:)
由于提供者将其作为 JSON 定义的字典起源,iOS 将其转换为NSDictionary
对象,没有像 那样的下标Dictionary
,但可以使用value(forKey:)
Reference from here
从这里参考
This's my way for Swift 4
这是我使用 Swift 4 的方式
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
guard application.applicationState == .active else { return }
guard let alertDict = ((userInfo["aps"] as? NSDictionary)?.value(forKey: "alert")) as? NSDictionary,
let title = alertDict["title"] as? String,
let body = alertDict["body"] as? String
else { return }
let alertController = UIAlertController(title: title, message: body, preferredStyle: .alert)
let okAct = UIAlertAction(title: "Ok", style: .default, handler: nil)
alertController.addAction(okAct)
self.window?.rootViewController?.present(alertController, animated: true, completion: nil)
completionHandler(UIBackgroundFetchResult.noData)
}
回答by Erik Peruzzi
This is my version for objC
这是我的 objC 版本
if (userInfo[@"aps"]){
NSDictionary *aps = userInfo[@"aps"];
if (aps[@"alert"]){
NSObject *alert = aps[@"alert"];
if ([alert isKindOfClass:[NSDictionary class]]){
NSDictionary *alertDict = aps[@"alert"];
if (alertDict[@"message"]){
NSString *message = alertDict[@"message"];
}
}
else if (aps[@"alert"]){
NSString *alert = aps[@"alert"];
}
}
}