Check if the user exists in Firebase (phone auth)

Viewed 494

I am writing an application on SwiftUI and Firebase. At the moment, I have implemented authentication by phone number. When a user enters a phone number, I get the phone number and id data in Firebase. But I also want to get a photo and a name from the user. I can implement this in a separate window. The problem is that if the user exits the application and logs in again, the application again asks him to upload a photo and write a name. Although the data about this user is already in Firebase. Is there a way after sending a message to check whether the user is registered or not to show or not to show an additional view with a photo and name request?

My function for sending code:

func sendCode() {
    
    self.isLoading.toggle()
    
    PhoneAuthProvider.provider().verifyPhoneNumber(phoneNumber, uiDelegate: nil) { (verificationId, error) in
        
        self.isLoading.toggle()
        
        if error != nil {
            self.isError.toggle()
            self.errorMsg = error?.localizedDescription ?? ""
            return
        }
        
        UserDefaults.standard.set(verificationId, forKey: "verificationId")
        self.isVerify.toggle()
    }
}

My function for verification:

func verifyCode(code: String, name: String, num: String) {
    self.isLoadingVerify.toggle()
    
    let verificationId = UserDefaults.standard.string(forKey: "verificationId") ?? ""
    let credentials = PhoneAuthProvider.provider().credential(withVerificationID: verificationId, verificationCode: code)
    
    Auth.auth().signIn(with: credentials) { (authResult, error) in
       
        self.isLoadingVerify.toggle()
        self.userSession = authResult?.user
        self.fetchUser()
        
        if error != nil {
            self.isError.toggle()
            self.errorMsg = error?.localizedDescription ?? ""
            return
        }
        guard let user = authResult?.user else { return }
        self.tempCurrentUser = user
        
//        self.userSession = user
        
        let data = ["name": name.lowercased(),
                     "uid": user.uid,
                     "num": num
        ]
        COLLECTION_USERS.document(user.uid).setData(data) { _ in
              self.fetchUser()
//            self.userSession = user
//            self.fetchUser()убрал после того как не загрузилось фото профиля
        }

        print(authResult ?? "")
        self.isVerify.toggle()
        self.isVerified.toggle()
        self.isPhotoName.toggle()
    }
    
}
1 Answers

Before you call signin, you can check if there is an already loggedin user. Check:

Auth.auth().currentUser != nil

And you can avoid signing in again. If the user exists you can get user Id from

Auth.auth().currentUser?.uid
Related