I'm currently investigating the same thing. My issue is that I also want persistence enabled, so I need to be aware of what can be accessed offline. If you're using persistence, I would also recommend disallowing particular operations such as checking username existence if your client is offline, which you can do by listening to ".info/connected" as further detailed here:
https://firebase.google.com/docs/database/ios/offline-capabilities#section-connection-state
My personal workflow for this is as follows:
- Login to user's account
- Check if the user already has a username
Check the firebase database to see if their user details includes a username:
DB/users/*userUID*/username != nil
- If they don't have a username, then prompt them to set a username.
When they set their username, check if the username exists in:
DB/usernames/*username*/ != nil
If it doesn't exist, then write the username and userId in the two database locations checked above.
eg.
user.uid = wewe32323
username = scuba_steve
DB/usernames/scuba_steve = wewe32323
DB/users/wewe32323/username = scuba_steve
So now you have the DB/usernames reference that you can check quickly to see if anyone has a username already, and you also have DB/users/ where you can quickly find a username for a given user.
I won't say this is fool-proof, as I still a few concerns around concurrent requests. My current issue I'm investigating is that lets say you delete the username association to a particular user, the user can depend on their local copy of the database to incorrectly assert that they are still assigned to that username.
You could look into the database write rules to disallow anyone to modify existing data (enforcing that you can only write to the DB/usernames directory if there is no existing data. This would prevent overriding of whoever sets the username first, which I think is an important step.
It may also be worth investigating Transactions:
https://firebase.google.com/docs/database/ios/save-data#save_data_as_transactions
But I believe correct write rules as mentioned in the paragraph above should allow dependable writing.