我有一個方法,當我打電話的NotificationCenter
POST方法:如何從通知中訪問userInfo屬性?
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)
}
一切都好,直到現在。這是我最後的方法,我試圖訪問用戶信息數據:
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 \ 「:\」 測試\」,\ n \ 「conv_token \」:\ 「測試\」,\ 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 \」idDestino \「:\」1 \「,\ n \」desDestino \「:\」ASUNCION \ 「\ n \」desDestino \「:\」MIAMI \「\ n} \ n] \ n \ n \ n \ n} \ n)」):「」]
第一個錯誤在我看來'[message.string! :String()]'是一個字典,其中消息字符串作爲*鍵,*和一個空字符串作爲值。這可能不是你想要的。 –
對不起...但是,當我嘗試不在通知中找到用戶信息時,可以以什麼方式幫助我? – xhinoda
將你的'guard let userInfo ....'語句分解爲兩部分,以便知道它是用戶信息問題還是「idDestino」問題。 –