当我调用NotificationCenter
的帖子方法时,我有一个方法:
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" } ] } } }
这是我的帖子方法声明:
func post(name: Notification.Name, userInfo info : [AnyHashable : Any]? = nil) {
NotificationCenter.default
.post(name: name, object: nil, userInfo: info)
}
直到现在一切都还可以。这是我尝试访问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”。有人可以帮帮我吗?
我的userInfo输出是:
[AnyHashable(“{\ n \”req_token \“:\”test \“,\ n \”conv_token \“:\”test \“,\ n \”ts \“:\”2017-04- 05 12:00:00.123 \“,\ n \”code \“:0,\ n \”message \“:\”ACCESO CONCEDIDO \“,\ n \”auth_token \“:\”jakldsfjalkdfj \“,\ n \“response \”:{\ n \“type \”:\“test \”,\ n \“data \”:{\ n \“destinos \”:[\ n {\ n \“idDestino \”: \“1 \”,\ n \“desDestino \”:\“ASUNCION \”\ n},\ n {\ n \“idDestino \”:\“2 \”,\ n \“desDestino \”:\“迈阿密\“\ n} \ n] \ n} \ n} \ n}”}):“”]
答案 0 :(得分:0)
好的......我解决了我的问题...感谢@martin R
问题在于这一行:
bus.post(name: .DestinationRespReceived, userInfo: [message.string! : String()])
我没有意识到密钥是我的userInfo的第一个元素,第二个元素是值。所以我更正了我的userInfo位置元素,如下所示:
bus.post(name: .DestinationRespReceived, userInfo: ["msg" : message.string!])
所以...在我的func responseReceived
中现在是正确的:
guard let userInfo = notification.userInfo, let msg = userInfo["msg"] as? String else {
Log.v("No userInfo found in notification")
callback.onResponseReceived(nil)
return
}
谢谢!