Searching through child values Firebase / Swift

前端 未结 2 845
孤街浪徒
孤街浪徒 2020-12-10 00:42

My database has values sorted like this :

 Users
    UID
      Username
      Email

I\'m wanting to implement a friend adding system where

2条回答
  •  温柔的废话
    2020-12-10 01:00

    Try this...

    Assume a structure (this is Swift 2, Firebase 2)

    users
      uid_0
        email: "someuser@thing.com"
        displayName: "some display name"
    

    and we want to get uid_0's info

    let displayName = "some display name"
    
    usersRef.queryOrdered(byChild: "displayName").queryEqual(toValue: displayName)
                  .observeSingleEvent(of: .childAdded) { (snapshot: FIRDataSnapshot) in {
    
         let dict = snapshot?.value as! [String: AnyObject]
         let email = dict["email"]
         let displayName = dict["displayName"]
         print(email!)
         print(displayName!)
    
         let key = snapshot?.key
         print(key!)
    }
    

    A couple things to note

    The 'dict' variable is being told it's being assigned a dictionary of type [String: Anyobject].

    Any Object could well, be any object. A String, another dictionary, an int. So you need to ensure you code can handle whatever the object is

    The snapshot key in this case is the snapshot of this user, and the key must be the parent node, which in this case is uid_0. So the output is

    someuser@thing.com
    some display name
    uid_0
    

    EDIT:

    Updated for Firebase 4, Swift 4 and handle the case where multiple children are returned

    let usersRef = self.ref.child("users")
    
    let input = "some display name"
    let query = usersRef.queryOrdered(byChild: "displayName").queryEqual(toValue: input)
    query.observeSingleEvent(of: .value, with: { snapshot in
        for child in snapshot.children {
            let snap = child as! DataSnapshot
            let dict = snap.value as! [String: Any]
            let email = dict["email"] as! String
            let displayName = dict["displayName"] as! String
            print(email)
            print(displayName)
    
            let key = snapshot.key
            print(key)
        }
    })
    

提交回复
热议问题