Firebase值返回nil

时间:2019-06-18 18:55:05

标签: swift firebase firebase-realtime-database

我有一个搜索栏,允许我通过用户名搜索用户。结果将显示一个空单元格,用户名返回nil。

我尝试将引用路径更改为ref.queryOrdered(byChild:"information"),并省略了名称,但这没有用。我也尝试过将参考路径用作ref.observeSingleEvent,但没有收到任何快照作为回报。

我寻求帮助的其他链接:

  1. Firebase Database suddenly returning nil
  2. Firebase Data Returning Nil
  3. Retrieving data from firebase returned nil

Firebase中users的json的设置如下:

{
  "UserId" : {
  "information" : {
  "name" : "bobby",
   },
 }
}  

下面的代码段:

class SearchUser {
     var id: String?
     var name: String?
}

extension SearchUser {

   static func setUser(dict: [String: Any], key: String) -> SearchUser 
{
    let user = SearchUser()
    user.id = key
    user.name = dict["name"] as? String

    return user
}

// MARK: Search for users
static func queryUsers(withText text: String, completion: @escaping 
(SearchUser) -> Void) {
    let ref = Database.database().reference().child("users")

 ref.queryOrdered(byChild: 
 "information/name").queryStarting(atValue: 
 text).queryEnding(atValue: text+"\u{f8ff}").queryLimited(toFirst: 
 10).observeSingleEvent(of: .value, with: { (snapshot) in
        snapshot.children.forEach({ (s) in
            //Snapshot displays the correct user info 
            print("Snapshot is: \(snapshot)")
            let child = s as! DataSnapshot
            if let dict = child.value as? [String: Any] {
                let user = SearchUser.setUser(dict: dict, 
             key: child.key)
                // Returns nil
                print("User is: \(String(describing: user.name))")
                // Will return correct ID
                print("User ID: \(String(describing: user.id))")
                completion(user)
            }
        })
    })
  }
}

我希望user.name返回用户名,但当前输出为nil。

0 个答案:

没有答案