Swift 如何从通知访问中的userInfo属性?
调用Swift 如何从通知访问中的userInfo属性?,swift,notifications,notificationcenter,userinfo,Swift,Notifications,Notificationcenter,Userinfo,调用通知中心的post方法时,我有一个方法: func processMessage(message: CocoaMQTTMessage) { Log.d("DestinationTopicHandler: handling message") //message.string: Contains the response of the server print(message.string!) // print the response (String) bu
通知中心的post方法时,我有一个方法:
func processMessage(message: CocoaMQTTMessage) {
Log.d("DestinationTopicHandler: handling message")
//message.string: Contains the response of the server
print(message.string!) // print the response (String)
bus.post(name: .DestinationRespReceived, userInfo: [message.string! : String()])
}
这里是我的message.string打印:
{
"req_token":"test",
"conv_token":"test",
"ts":"2017-04-05 12:00:00.123",
"code":0,
"message":"ACCESO CONCEDIDO",
"auth_token":"test",
"response":{
"type":"test",
"data":{
"destinos":[
{
"idDestino":"1",
"desDestino":"ASUNCION"
},
{
"idDestino":"2",
"desDestino":"MIAMI"
}
]
}
}
}
直到现在一切都很好。这是我尝试访问userInfo数据的最后一种方法:
public func responseReceived(_ notification: Notification) {
if processed {
return
}
processed = true
responseReceived = true
Log.i("responseReceived:")
guard let userInfo = notification.userInfo, let msg = userInfo["idDestino"] as? String else {
Log.v("No userInfo found in notification")
callback.onResponseReceived(nil)
return
}
if let json = msg.json {
callback.onResponseReceived(Response_Base(json: json.dictionary))
} else {
Log.v("Could not parse msg")
callback.onResponseReceived(nil)
}
}
问题是我不知道为什么程序总是返回“通知中找不到用户信息”。有人能帮我吗
我的userInfo输出是:
[AnyHashable(“{\n\”req\ U token\”:“test\”,\n\“conv\ U token\”:“test\”,\n\“ts\”:“2017-04-05 12:00:00.123\”,\n\“code\”:0、\n\“message\”:“ACCESO CONCEDIDO\”,\n\“auth\ U token\”:“JAKLDSFJ\”,\n\“response\”,\n\“type\”:“test\”,\n\”,\n\“data\”:\n\”:\nidDestino\:“1\”,\n\“desDestino\”:“亚松森”\n}、\n{\n\“idDestino\”:“2\”,\n\“destino\”:“迈阿密”\n}\n}\n}:“]
好的……我解决了我的问题……感谢@martin R
问题在于这一行:
bus.post(name: .DestinationRespReceived, userInfo: [message.string! : String()])
我没有意识到key是userInfo的第一个元素,第二个元素是value。因此,我更正了我的userInfo位置元素,如下所示:
bus.post(name: .DestinationRespReceived, userInfo: ["msg" : message.string!])
因此…在我的函数中,收到的响应现在是正确的:
guard let userInfo = notification.userInfo, let msg = userInfo["msg"] as? String else {
Log.v("No userInfo found in notification")
callback.onResponseReceived(nil)
return
}
谢谢 在我看来,第一个错误是[message.string!:string()]
是一个字典,消息字符串作为键,空字符串作为值。这可能不是你想要的。对不起……但当我尝试在“通知中找不到用户信息”中不掉时,有什么方法可以帮助我?将你的guard let userInfo….
语句分成两部分,这样你就知道这是用户信息问题还是“idDestino”问题了。
guard let userInfo = notification.userInfo, let msg = userInfo["msg"] as? String else {
Log.v("No userInfo found in notification")
callback.onResponseReceived(nil)
return
}