I began to study development for iOS for several weeks and when creating my first application I had to solve the issue with the implementation of "User Authorization"
For these purposes, I chose Firebase
And then such a question arose, because when registering a user, I save his email and login to the database, and it was necessary to set up a method that, when you click on the "register" button, will check that such an email and login are not in the database, and only then go on.
Having studied the Firebase documentation and watched some videos on this service, I tried to solve this problem as follows:
private func isNewEmail(_ email: String, completion: _ emailIsNew: Bool -> ()) {
ref = Database.database().reference(withPath: "users")
ref.getData { error, snapshot in
var emailIsNew: Bool = true
guard error == nil else { return }
guard let snapshotValue = snapshot.value as? [String : AnyObject] else {
if snapshot.value as? [String : AnyObject] == nil {
completion(emailIsNew)
return
}
return
}
for item in snapshotValue {
let itemValueDictionary = item.value
guard let emailFromDatabase = itemValueDictionary["email"] as? String else { return }
if email.lowercased() == emailFromDatabase.lowercased() {
emailIsNew = false
break
}
}
completion(emailIsNew)
}
}
Next, we call the method described above, and pass the email there, and depending on the value of emailIsNew, we either create or do not create a user.
The most important problem: I assumed that if we have, for example, 10,000 users in our database, then such a check can take a very long time, it seems to me that when a person clicks "Register" and then waits 10 minutes for the application to check everything - this is unacceptable, so I tried to find another way to solve the original problem, but unfortunately, I could not find it due to, I suppose, a small amount of experience. I ask you to suggest how to solve this problem, how you can change the verification method, or in general, perhaps, apply something else.
MARK - I studied similar answers on stackoverflow, but most of them were relevant for android or Java, or I could not apply the solutions to solve my problem. Because I am only studying English, then perhaps this was the reason that I could not find the answer, but still, I would like to receive a comment on my method, along with links to a similar question. Thank you for understanding.
CodePudding user response:
If each child of your users
has an email
property with the value you want to check, you can use a query to just retrieve the matching nodes.
Something like:
var query = ref.queryOrdered(byChild: "email").queryEqual(toValue: email.lowercased())
query.getData { error, snapshot in
...
Since all searches in Firebase are case-sensitive, this does require that your database contains all email addresses in lowercase already. If that's not the case, consider adding a property (say email_lowercase
) with the lowercase value and using that in the query above.