2017-04-18 138 views
0

我試圖獲取值居住使用此功能:斯威夫特IOS火力地堡不返回任何數據

handle = ref?.child("Users").child(String(itemId)).observe(.childChanged, with: { (snapShot) in 

         if let dictionary = snapShot.value as? [String: Any] { 
          print(dictionary) 
          if let profileImageUrl = dictionary["url"] as? String { 
           print(profileImageUrl) 
          } 
         } 
        }, withCancel: nil) 

我開始我的應用程序,然後我去我的火力控制檯和做一些改變這個孩子,但我print()從未被解僱。

這是我的數據庫看起來像:

MyRootDb123 
-Users 
    --Id (Child of users) 
    --- url inside Id 
    --- name inside Id 
    --- age inside Id 

而且在我的代碼,什麼是withCancel功能嗎?

DB結構: enter image description here

更新 我加print(snapShot)返回:

Snap (url) www.someurl.com 
+0

哪一個不會觸發'print(dictionary)'? –

+0

@NazmulHasan沒有人被解僱,如果讓字典= snapShot.value爲? [String:Any] {''我認爲我不能使用[String:Any] – Kiow

+0

@NazmulHasan我添加了'print(snapShot)',它返回: Snap(url)www.someurl.com – Kiow

回答

0

火力地堡是大小寫敏感的節點鍵名稱,以便用戶是不一樣的用戶並且您的代碼正在訪問用戶,但結構是Users。

代碼

handle = ref?.child("users") 

結構

MyRootDb123 
-Users 
    --Id (Child of users) 

更新展示如何將.childChanged觀察者附加到用戶節點和處理的改變給用戶。

讓我們先從基本的火力地堡結構

users 
    uid_0 
    name: "Leonard" 
    url: "www.leonard.com 
    uid_1 
    name: "Bill" 
    url: "www.bill.com" 

然後我們附上.childChanged觀測到用戶節點。當用戶節點中的子節點發生更改時,更改的節點將傳遞給閉包。

let usersRef = self.ref.child("users") 

usersRef.observe(.childChanged, with: { snapshot in 
    let userDict = snapshot.value as! [String: AnyObject] 
    let name = userDict["name"] as! String 
    let url = userDict["url"] as! String 
    print("\(name) now has url of: \(url)") 
}) 

爲了驗證這一點,在火力地堡控制檯我們改變uid_0的URL孩子從www.leonard.com到www.yipee.com,這樣

users 
    uid_0 
    name: "Leonard" 
    url: "www.yipee.com" //here's the new url 
    uid_1 
    name: "Bill" 
    url: "www.bill.com" 

由於變化是uid_0 ,它傳遞給上面代碼中的封閉節點,並將打印:

Leonard now has url of: www.yipee.com 
+0

我在我的文章中犯了一個錯字。當我調用print(snapShot)''它輸出**「Snap(url)www.someurl.com」**時,我的代碼似乎很有用,但我不明白我如何檢查我的節點是否有特定的值。當我通過控制檯更改我的「url」值時,上面的輸出被打印出來 – Kiow

+0

@Kiow屏幕截圖顯示*用戶*,您的代碼顯示*用戶*。它是區分大小寫的,不會與該錯誤一起工作。當您打印(快照)時,它將打印從Firebase檢索到的數據 - 因爲快照是空白的,它不會打印任何內容。該代碼正在運行,但沒有*工作*,因爲由於錯字而無法從Firebase返回任何內容。修復你的文章和你的代碼中的錯字,我們再看看這個問題。 – Jay

+0

我現在已經修復了我的錯字 – Kiow

相關問題