Querying Firebase Users to Check If Contact Exists

2019-04-17 01:04发布

I am currently setting up a Firebase app and am able to retrieve a list of all users who use the app. When a user first signs up for the app they are required to confirm their phone number as most iOS apps do these days. I am storing their phone number in the "users" node. My question is how do I query in Firebase to check to see if that phone number exists within my database? Basically I want to query against a list of phone numbers that I'm generating against the list of all contacts

This will allow me to display if a specific contact is currently using the app, it will show up underneath the contact name in a tableview / collectionview. If they aren't then they could receive an invite to join the app via text / email.

The "users" node is displayed in my Firebase database as the following:

    "users" : {
    "userId1" : {
        "name" : "Alex",
        "email" : "alex@gmail.com",
        "phoneNumber" : "123456789" 
    },  
    "userId2" : {
        "name" : "Ben",
        "email" : "ben@gmail.com",
        "phoneNumber" : "223456789" 

    },
    "userId3" : {
        "name" : "Charles",
        "email" : "charles@gmail.com",
        "phoneNumber" : "323456789" 

    }
}

I am new to querying in a nosql database and would appreciate the help. Thank you so much!

2条回答
Viruses.
2楼-- · 2019-04-17 01:32

Try using Firebase's sort functionalities.

var userRef : FIRDatabaseQuery = FIRDatabase.database().reference().child("users")
userRef = userRef.queryOrdered(byChild: "phoneNumber").queryEqual(toValue: <NUMBER>)
userRef.observe(FIRDataEventType.value, with: { (snapshot) in
    if snapshot.value != nil {
        //value exists
    }
}, withCancel: { (error) in
    //search error
})

More information for sorting is here: https://firebase.google.com/docs/database/ios/lists-of-data

查看更多
三岁会撩人
3楼-- · 2019-04-17 01:39

First, fetch the value from firebase and check if it exists or not. Below is the sample code

   self.ref = FIRDatabase.database().reference()
    ref.child("users").child("userID").observeSingleEventOfType(.Value, withBlock: { (snapshot) in

        if snapshot.hasChild("phoneNumber"){

            print("Phone number exist")

        }else{

            print("Phone number doesn't exist")
        }


    })

Another way: Going directly with the path and checking existence

FIRDatabase.database().reference().child("users").child("userID").child("phoneNumber").observeSingleEvent(of: .value, with: {(snap) in

        if snap.exists(){

            //Your user already has a Phone number

        }else{
           //Phone number not available

        }
    })
查看更多
登录 后发表回答