2017-07-19 36 views
0

我有一個方法,當我打電話的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)」):「」]

+1

第一個錯誤在我看來'[message.string! :String()]'是一個字典,其中消息字符串作爲*鍵,*和一個空字符串作爲值。這可能不是你想要的。 –

+0

對不起...但是,當我嘗試不在通知中找到用戶信息時,可以以什麼方式幫助我? – xhinoda

+0

將你的'guard let userInfo ....'語句分解爲兩部分,以便知道它是用戶信息問題還是「idDestino」問題。 –

回答

0

OK ...我解決了我的問題...感謝@馬丁R

問題是這一行:

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

我不知道,關鍵是我的用戶信息的第一個元素和第二個元素是值。所以我糾正我的我的用戶信息位置的元素是這樣的:

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 
    } 

謝謝!