ksa_coder
ksa_coder

Reputation: 1403

Firebase - Check efficiently username taken

I developed a small function that checks if the username entered by registering guest is available or not. Nonetheless, the function checks this locally on the device using the iteration and if condition. I am thinking this may become a performance bottleneck in future when there are thousands of users in that list (the list is updated every time a new user is created successfully). Is there a way I can do this more efficiently on the backend side?

Here is the function that works now:

func checkUsernameTaken(completion: (result: NSError) -> Void)
    {
        let errorFound:NSError = NSError(domain: "", code: 0, userInfo: nil)

        dbReference.child("usernamesTaken").observeEventType(.Value, withBlock: { (snapshot: FIRDataSnapshot!) -> Void in
            if(snapshot != nil )
            {
                for rest in snapshot.children.allObjects as! [FIRDataSnapshot]  {
                    if(rest.value as? String == self.usernameTxtField.text!){
                        self.isUsernameTaken = true
                    }else{
                        self.isUsernameTaken = false
                    }
                }
                completion(result:errorFound)
            }else{
                self.isUsernameTaken = false
                completion(result:errorFound)
            }
        })
    }

The data structure in Firebase is this:

the alpha numeric is supposedly the UID and the username is admin

This list will grow as said earlier but for now it is short for testing purposes only.

Thanks in advance

Update:

 func usernameValidation(completion: (result: NSError) -> Void)
    {
        let errorFound:NSError = NSError(domain: "", code: 0, userInfo: nil)

        dbReference.child("usernamesTaken").queryEqualToValue(self.usernameTxtField.text!).observeEventType(.Value, withBlock: { (snapshot: FIRDataSnapshot!) -> Void in

            print(snapshot.childrenCount)
        })
    }

Upvotes: 0

Views: 203

Answers (1)

Travis
Travis

Reputation: 2462

Instead of doing the search yourself, let Firebase execute a query. FIRDatabaseQuery allows you to order and filter children by key or value. In your case you can use queryEqualToValue to find children of usernamesTaken that match usernameTxtField.text.

Upvotes: 3

Related Questions