2017-04-13 132 views
1

我一直在尋找遍及互聯網和堆棧溢出,但沒有找到任何我理解得足夠好的東西來實現我的解決方案。 這裏有很多類似的問題,但沒有一個建議的解決方案爲我工作,所以我會問你們。Swift:爲用戶搜索Firebase數據庫

如何在swift中搜索我的Firebase數據庫中的用戶名? 在我的應用程序中,我有一個視圖,應該允許用戶搜索數據庫中的好友。結果應該實時更新,這意味着每次用戶鍵入或刪除結果應該更新的字符。到目前爲止,我所有的都是一個UISearchBar,並且沒有後端代碼。

因爲我不知道創建這樣一個功能需要什麼,所以如果你們能告訴我你需要告訴我到底該做什麼,那將是很酷的。 (數據庫結構,代碼部分...)。我不想在這裏複製和粘貼無用的東西。

我真的很感謝幫助。

編輯:

這是我的數據庫結構:

"users" 
    "uid" // Automatically generated 
     "goaldata" 
      "..." // Not important in this case 
     "userdata" 
      "username" 
      "email" 
      "country" 
      "..." // Some more entries not important in this case 

希望我這樣做是正確的,真的不知道如何發佈這個放在這裏。

+0

可以請您展示Firebase數據庫結構,只有這樣纔有可能確定適用的查詢。 –

+0

@JenJose會做,只是一秒鐘。 – dantheputzer

+0

@JenJose你走了,我希望能完成這項工作。 – dantheputzer

回答

4

假設火力地堡結構是這樣的

實施例1:

users 
    -> uid 
     ->otherdata 
     ->userdata 
      ->username : "jen" 
      -> other keys 

    -> uid2 
     ->otherdata 
     ->userdata 
      ->username : "abc" 
      -> other keys 

並查詢基於用戶名,我們需要在queryOrdered查詢(byChild: 「用戶數據/用戶名」)。 queryStarting & queryEndingAt,提取從「je」開始的所有名稱,並且這個「\ uf8ff」表示*(任何)。

let strSearch = "je" 
baseRef.child("users").queryOrdered(byChild: "userData/username").queryStarting(atValue: strSearch , childKey: "username").queryEnding(atValue: strSearch + "\u{f8ff}", childKey: "username").observeSingleEvent(of: .value, with: { (snapshot) in 
     print(snapshot) 
    }) { (err) in 
     print(err) 
} 

如果用戶名是直接在用戶節點的下方,然後嘗試這個

實施例2:

users 
    -> uid 
     ->username : "jen" 
     -> other keys 

    -> uid2 
     ->username : "abc" 
     -> other keys 

的查詢將被改組如下,

let strSearch = "je" 
baseRef.child("users").queryOrdered(byChild: "username").queryStarting(atValue: strSearch).queryEnding(atValue: strSearch + "\u{f8ff}").observeSingleEvent(of: .value, with: { (snapshot) in 

    print(snapshot) 

}) 

請注意這種方法是區分大小寫。搜索String =「je」和「Je」的搜索結果將有所不同,查詢將與案例匹配。

+0

非常感謝@JenJose!我會盡快找到我的電腦。我會盡快給您回覆! – dantheputzer

+0

如何將其鏈接到UISearchBar?對不起,我很小菜:) – dantheputzer

+0

你必須appy在func searchBar(searchBar:UISearchBar,textDidChange searchText:String){}委託方法,並根據搜索結果重新加載表。 –