2014-07-22 26 views
32

我有發送通知(其中SERIALNUMBER是一個字符串)代碼:如何訪問經由NSNotification傳遞Dictionary,使用夫特

func deviceActivity(notification: NSNotification) { 

    // This method is invoked when the notification is sent 
    // The problem is in how to access the Dictionary and pull out the entries 
    } 

var dataDict = Dictionary<String, String>() 
    dataDict["Identity"] = serialNumber 
    dataDict["Direction"] = "Add" 
      NSNotificationCenter.defaultCenter().postNotificationName("deviceActivity", object:self, userInfo:dataDict) 
接收到該通知

和代碼我試過了各種代碼來完成這個,但沒有成功:

let dict = notification.userInfo 
let dict: Dictionary<String, String> = notification.userInfo 
let dict: Dictionary = notification.userInfo as Dictionary 

雖然我的一些

let sn : String = dict["Identity"]! 
let sn : String = dict.valueForKey("Identity") as String 
let sn : String = dict.valueForKey("Identity") 

所以,問題是這樣的:嘗試滿足編譯器,還沒有試圖訪問哪些已被提取爲字典時產生實際字符串我怎樣寫斯威夫特代碼解壓到一個對象,在這種情況下,字典,通過通知傳遞,並訪問該對象的組件部分(在這種情況下,鍵和值)?

回答

36

由於notification.userInfo類型是AnyObject,所以您必須將其向下轉換爲適當的字典類型。

確定字典的確切類型後,您不需要貶低您從中獲得的值。但是你可能要檢查是否值在字典中確實存在使用前:

// First try to cast user info to expected type 
if let info = notification.userInfo as? Dictionary<String,String> { 
    // Check if value present before using it 
    if let s = info["Direction"] { 
    print(s) 
    } 
    else { 
    print("no value for key\n") 
    } 
} 
else { 
    print("wrong userInfo type") 
} 
+0

這工作,謝謝! – user3864657

+0

總是打印(「錯誤的userInfo類型」) - 在swift 2 –

+0

@異步 - 它適用於我在操場上。您需要確保所有的鍵和值都是字符串。如果你有不同的類型,你將需要在第一個劇組中改變類型 – Vladimir

12

你應該用結構像[NSObject : AnyObject]和檢索值從NSDictionary的yourLet[key]

func keyboardWillShown(notification : NSNotification){ 
    let tmp : [NSObject : AnyObject] = notification.userInfo! 
    let duration : NSNumber = tmp[UIKeyboardAnimationDurationUserInfoKey] as NSNumber 
    let scalarDuration : Double = duration.doubleValue 
}