Firebase create user with email, password, display name and photo url

后端 未结 6 1151
死守一世寂寞
死守一世寂寞 2020-12-15 07:17

According to Firebase site, I am using this code to create a new user:

firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error)          


        
相关标签:
6条回答
  • 2020-12-15 07:36

    I think you mean adding display name and photo url to Firebase Database after Auth. This is pretty much what I do all on same registration.

       if let email = emailField.text where email != "", let pwd = passwordField.text where pwd != ""{
    
            FIRAuth.auth()?.createUserWithEmail(email, password: pwd, completion: { (user, error) in
                if error != nil {
                    print("DEVELOPER: Unable to authenticate with Firebase using email")
                }else {
                    print("DEVELOPER: Successfully authenticated with Firebase using email")
                    if let user = user {
                        let userData = ["provider": user.providerID, "userName": "\(user.displayName)", "profileImg": "\(user.photoURL)"]
                        self.completeMySignIn(user.uid, userData: userData)
                    }
                }
            })
    
         } else {
           // Email and Password where not filled in
        }
    }
    

    Now adding your profile image and users username in DB here

    func completeMySignIn(id: String, userData: Dictionary<String, String>){
        {YourFirebaseUserURL}.updateChildValues(userData)
    }
    
    0 讨论(0)
  • 2020-12-15 07:37

    You can update your profile with FIRUserProfileChangeRequest class .. check this Doc.

    let user = FIRAuth.auth()?.currentUser
       if let user = user {
          let changeRequest = user.profileChangeRequest()
    
          changeRequest.displayName = "Jane Q. User"
          changeRequest.photoURL =
              NSURL(string: "https://example.com/jane-q-user/profile.jpg")
          changeRequest.commitChangesWithCompletion { error in
            if let error = error {
              // An error happened.
            } else {
              // Profile updated.
            }
          }
        }
    
    0 讨论(0)
  • 2020-12-15 07:38

    Simply you can solve your problem as follow.

    1) Create a user using following statement.

    firebase.auth().createUserWithEmailAndPassword(email, password).catch(function(error) {});
    

    2) success of above statement Please authenticate this user as follow.

         self.rootRef.authUser(email, password)
     // USER_ID = Here you get user_ID
    

    3) Success of above function set user name and profile picture to user as follow.

      usersRef.updateChildValues(dict, withCompletionBlock:
    

    -Here userRef contain your userDetails/USER_ID

    Might be work for you. i have code but work for older firebase version so not work for you otherwise i had share with you.

    0 讨论(0)
  • 2020-12-15 07:48

    I think this should solve it for you, let me know if you need anything else. or have any further questions on this matter.

        func handleSignUp() {
        guard let userName = userNameTF.text else { return }
        guard let email = emailTF.text else { return }
        guard let password = passwordTF.text else { return }
        guard let image = profileImage.image else { return }
    
        continueButton.setBackgroundImage(#imageLiteral(resourceName: "inactiveButtonBG"), for: .normal)
        activityIndicator.startAnimating()
    
            Auth.auth().createUser(withEmail: email, password: password) { user, error in
                if error == nil && user != nil {
                    print("User created!")
                    self.uploadProfileImage(image: image) { url in
    
                        if url != nil {
                            let changeRequest = Auth.auth().currentUser?.createProfileChangeRequest()
                            changeRequest?.displayName = userName
                            changeRequest?.photoURL = url
    
                            changeRequest?.commitChanges { error in
                                if error == nil {
                                    self.saveProfile(username: userName, profileImageURL: url!) { success in
                                        if success {
                                            print("Success upload of profile image")
                                            self.dismiss(animated: true, completion: nil)
                                        }
                                    }
                                    self.dismiss(animated: true, completion: nil)
                                } else {
                                    guard let message = error?.localizedDescription else { return }
                                    self.userAlert(message: message)
                                }
                            }
                        } else {
                            self.userAlert(message: "Unable to load profile image to Firebase Storage.")
                        }
                    }
    
                    self.dismiss(animated: true, completion: nil)
                } else {
                    guard let message = error?.localizedDescription else { return }
                    self.userAlert(message: message)
                }
            }
    
    }
    
    0 讨论(0)
  • 2020-12-15 07:52

    To change/add the display name:

    user!.createProfileChangeRequest().displayName = "Your name"

    To change/add photoURL

    user!.createProfileChangeRequest().photoURL = URL(string: "image url")

    0 讨论(0)
  • 2020-12-15 07:55

    You can use the Firebase Admin SDK in Firebase Function exactly for your purpose, i.e. to fill up other user properties as the user is created:

    const admin = require("firebase-admin");
    
    // Put this code block in your Firebase Function:
    admin.auth().createUser({
            email: email,
            emailVerified: false,
            password: password,
            displayName: `${fname} ${lname}`,
            disabled: false
        })
    

    But creating user with Firebase Admin SDK may give you problem in sending email verification because the promise does not return the User object that has the sendEmailVerification() method. You may eventually need to use the Firebase client API (as shown in your own code) to create the user and update the user profile before sending the email verification:

    var user = firebase.auth().currentUser;
    
    user.updateProfile({
      displayName: "Jane Q. User",
      photoURL: "https://example.com/jane-q-user/profile.jpg"
    }).then(function() {
      // Update successful.
    }).catch(function(error) {
      // An error happened.
    });
    

    It make sense to update the displayName before sending email verification so that the Firebase email template will greet the new user with proper name rather than just Hello (sounds like a spam) when the displayName is not set.

    0 讨论(0)
提交回复
热议问题