2016-10-19 30 views
1

我從Firebase收到以下數據。我已經使我的snapshotValue NSDictionary。在Swift 3.0中訪問嵌套的NSDictionary值

enter image description here

self.ref.child("users").child(facebookID_Firebase as! String).observeSingleEvent(of: .value, with: { (snapshot) in 
      let snapshotValue = snapshot.value as? NSDictionary 
      print(snapshotValue, "snapshotValue") 
      //this line of code doesn't work 
      //self.pictureURL = snapshot["picture"]["data"]["url"] 
     }) { (error) in 
      print(error.localizedDescription) 
     } 

我試過How do I manipulate nested dictionaries in Swift, e.g. JSON data?How to access deeply nested dictionaries in Swift,和其他解決方案還沒有運氣。

如何訪問數據鍵和圖片鍵內的url值?

我可以在Firebase中創建另一個引用並獲取值,但我試圖保存另一個請求。

+0

BTW,當你再拍參考火力地堡不發出另一個請求。所有這些mombo jambo都由Firebase客戶端自己處理。 –

+0

@CemalEker Oh gotcha!我誤解了這個問題。 –

+0

請檢查這個答案 https://stackoverflow.com/a/43715807/3806350 –

回答

1

當你在swift中引用一個Dictionary的鍵時,你會得到一個未包裝的值。這意味着它可以是零。你可以強制打開這個值,或者你可以使用漂亮if let =

這應該可能工作。

if let pictureUrl = snapshot["picture"]["data"]["url"] { 
    self.pictureURL = pictureUrl 
} 
+0

嘿先生,不幸的是我得到以下內容:類型'FIRDataSnapshot'沒有下標成員 –

+0

如何繼續?我目前在看:http://stackoverflow.com/questions/39136026/type-any-has-no-subscript-members-firebase –

+0

那肯定不是一個字典呢。使用'childSnapshotForPath:'方法並創建一個新的快照。 'childSnapshotForPath:「picture.data.url」' –

0

嘗試使用: -

if let pictureDict = snapshot.value["picture"] as? [String:AnyObject]{ 

     if let dataDict = pictureDict.value["data"] as? [String:AnyObject]{ 

       self.pictureURL = dataDict.value["url"] as! String 

      } 
    } 
0

在線詞典解包:

let url = ((snapshot.value as? NSDictionary)?["picture"] as? NSDictionary)?["url"] as? String