2016-03-19 48 views
0

我試圖通過用戶註冊時自動保存的lowercaseString名稱來查詢用戶。事情是我正在爲使用他們的用戶名的用戶創建密鑰。現在我無法讓其他用戶找到他們的朋友,因爲我所有的人都是第一個關鍵的「用戶」。這裏是我的火力信息... Firebase data of user with keys: caseUsername, displayName, follows, and image使用Swift以唯一的UID作爲密鑰來查詢Firebase中的用戶

這裏是我的代碼...

let userRef = self.ref.childByAppendingPath("users") 
userRef.queryOrderedByChild("caseUsername") 
     .queryStartingAtValue(self.searchTXTFLD.text?.lowercaseString, childKey: "caseUsername") 
     .observeEventType(.Value, withBlock: { (snapshot) -> Void in 
      print(snapshot.key) 

請幫我用self.searchTXTFLD.text?.lowercaseString找到用戶。它應該等於用戶子女caseUsername

+2

您已經在您的問題中包含了JSON樹的圖片。請將實際的JSON替換爲文本,您可以通過點擊Firebase數據庫中的導出按鈕輕鬆獲取該文本。將JSON作爲文本可以搜索,使我們能夠輕鬆使用它來測試您的實際數據,並將其用於我們的答案中,並且通常只是一件好事。 –

回答

2

由於@Frank麪包車Puffelen。答案更多地體現了Firebase數據的結構。我沒有完全使用你的答案,但這裏是我擁有的和有效的。

@IBAction func searchFriendsACTN(sender: AnyObject) 
     { 
      let queryRef = self.ref.childByAppendingPath("users") 
      queryRef.queryOrderedByChild("caseUsername") 
       .queryEqualToValue(self.searchTXTFLD.text?.lowercaseString) 
       .queryLimitedToFirst(1) 
       .observeEventType(.Value, withBlock: { snapshot in 
        if snapshot.exists() 
        { 
         var newIds = [String]() 
         var newNames = [String]() 
         var newCsnames = [String]() 
         var newPics = [String]() 
         for items in snapshot.value as! NSDictionary 
         { 
          let ids = items.key 
          let names = items.value["displayName"] as! String 
          let csnames = items.value["caseUsername"] as! String 
          let pics = items.value["image"] as! NSString 

          newIds.append(ids as! String) 
          newNames.append(names) 
          newCsnames.append(csnames) 
          newPics.append(pics as String) 
         } 
         self.caseUserNameArray = newCsnames 
         self.usersID = newIds 
         self.usernameArray = newNames 
         self.photos = newPics 
         self.friendsTBLVW.reloadData() 
        } 
       }) 
     } 
1

當您有查詢時,可能有多個子項匹配條件。當您再監聽.Value事件時,Firebase將返回包含匹配子項列表的快照。即使只有一個匹配的孩子,它仍然會在列表中。

所以解決的辦法是遍歷匹配孩子:

ref.queryOrderedByChild("caseUsername") 
    .queryStartingAtValue(self.searchTXTFLD.text?.lowercaseString, childKey: "caseUsername") 
    .observeEventType(.Value, withBlock: { snapshot in 
     for child in snapshot.children { 
      print(child.key); 
     } 
    }); 
相關問題