V
V
Vladislav Resly2021-11-17 15:57:38
iOS
Vladislav Resly, 2021-11-17 15:57:38

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)
      }
}


Next, we respectively call the method described above and pass email there, and depending on the value of emailIsNew, we already create or do not create a user.

*SMALL MARK - as I study everything not so long ago, in the code I comment a lot for myself, for true programmers it may seem a little funny, but it’s actually easier to perceive and remember the information and the solutions used.

The main problem:I assumed that if we have 10,000 users in the database, for example, 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 until the application checks everything, this is unacceptable, therefore I tried to find another way to solve the original problem, but unfortunately, I could not find it due to, I believe, a small amount of experience. Please tell me how to solve this problem, how to change the verification method, or in general, perhaps, apply something else.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Alexander Prokhorovich, 2021-11-18
@alexgp13

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.

R
Ronald McDonald, 2021-11-17
@Zoominger

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 question

Ask a Question

731 491 924 answers to any question