Answer the question
In order to leave comments, you need to log in
How to organize a check in the Firebase database for the uniqueness of the data entered by the user?
Greetings, I started studying 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 in general everything went well initially, although many people sin on this service to work with it seemed to me quite convenient and pleasant (Perhaps due to the fact that I have not yet applied other solutions, I don’t know)
And then the following question arose, because when registering a user, I save his email and login to the database, and it was necessary to set up a certain a method that, when you click on the "registration" button, will check that such an email and login are not in the database, and only then move on.
Having studied the Firebase documentation and watched some videos on this service, I tried to solve this problem as follows:
// создаем метод, в который будем передавать введенный email и комплишнХандлер для обработки
private func isNewEmail(_ email: String, completion: _ emailIsNew: Bool -> ()) {
ref = Database.database().reference(withPath: "users")
// методом Firebase получаем данные из базы
ref.getData { error, snapshot in
// значение, которое отвечает за "новизну" email. Если true - значит такого email еще нет в базе.
var emailIsNew: Bool = true
guard error == nil else { return }
// получаем значение из нашего снэпшота и пытаемся скастить до словаря
guard let snapshotValue = snapshot.value as? [String : AnyObject] else {
// если у нас база пустая, значение будет nil, а значит любой email будет уникальным и можно передавать в
// хэндлер нашу переменную, созданную выше, со значением true (установлено по умолчанию
if snapshot.value as? [String : AnyObject] == nil {
completion(emailIsNew)
return
}
return
}
// запускаем цикл, где обрабатываем наши словари (т.к. snapshot.value вернет словарь словарей
for item in snapshotValue {
let itemValueDictionary = item.value
guard let emailFromDatabase = itemValueDictionary["email"] as? String else { return }
// тут мы сравниваем наши емайлы, если совпадение есть, меняем нашу переменную на false и делаем brake
if email.lowercased() == emailFromDatabase.lowercased() {
emailIsNew = false
break
}
}
// после цикла передаем в хэндлер наше значение переменной выше
completion(emailIsNew)
}
}
Answer the question
In order to leave comments, you need to log in
And what for to sort out records in a cycle? Doesn't Firebase know how to work with selection (where)? It seems like any database, the corresponding instruction must be supported, in a split second you will receive only a record with the desired e-mail (or an empty response), even if there are several million users in the database.
ps I have not worked with Firebase, but common sense and Google suggest that search in the database is supported.
I can't speak for FireBase, but in such cases they usually make such a column unique and catch the "Record already exists" exception on the application side. Will it go?
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question