簡體   English   中英

如何從通知中訪問userInfo屬性?

[英]How to access userInfo property in from a Notification?

我在調用NotificationCenter的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"
            }
         ]
      }
   }
}

這是我的post方法聲明:

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 \\“:\\”測試\\“,\\ n \\” conv_token \\“:\\”測試\\“,\\ n \\” ts \\“:\\” 2017-04-05 12: 00:00.123 \\“,\\ n \\”代碼\\“:0,\\ n \\”消息\\“:\\” ACCESO CONCEDIDO \\“,\\ n \\” auth_token \\“:\\” jakldsfjalkdfj \\“,\\ n \\”響應\\“:{\\ n \\” type \\“:\\”測試\\“,\\ n \\”數據\\“:{\\ n \\” destinos \\“:[\\ n {\\ n \\” idDestino \\“:\\” 1 \\“,\\ n \\” desDestino \\“:\\” ASUNCION \\“ \\ n},\\ n {\\ n \\” idDestino \\“:\\” 2 \\“,\\ n \\” desDestino \\“:\\” MIAMI \\“ \\ n} \\ n] \\ n} \\ n} \\ n}“):”“]

好...我解決了我的問題...感謝@martin R

問題是這一行:

 bus.post(name: .DestinationRespReceived, userInfo: [message.string! : String()])

我沒有意識到,鍵是我的userInfo的第一個元素,第二個元素是值。 所以我像這樣糾正我的userInfo位置的元素:

bus.post(name: .DestinationRespReceived, userInfo: ["msg" : message.string!])

所以...在我的函數responseReceived中,Received現在是正確的:

 guard let userInfo = notification.userInfo, let msg = userInfo["msg"] as? String else {

            Log.v("No userInfo found in notification")
            callback.onResponseReceived(nil)

            return
    }

謝謝!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM