I tried running the following and it does not work. What am I doing wrong to check the Firebase server if the user has already used the email?
FIRAuth.auth()!.createUser(withEmail: self.userEmailTextField.text!, password: self.userPasswordTextField.text!) {(createUser, error) in
if error != nil {
FIRAuth.auth()!.signIn(withEmail: self.userEmailTextField.text!, password: self.userPasswordTextField.text!)
//Display logged in
let viewController = self.storyboard!.instantiateViewController(withIdentifier: "TabBarController") as UIViewController
self.present(viewController, animated: true, completion: nil)
}else {
//Display an alert message
self.displayMyAlertMessage(userMessage: "Email already in use. Please see the login page.")
return
}
}
Please refer below code.
Code:
FIRAuth.auth()?.createUser(withEmail: email, password: password) {
(user, error) in
if (error) {
// Email is already in use.
} else {
// Create new user successfully
}
}
Handle Firebase iOS Auth Errors
Firebase already does this for you. Erase the sign in method and just run the create user method using an email that already exists and FIRAuthErrorCodeEmailAlreadyInUse will be returned. Check this out for more info
Related
I am trying to login to my user after updating firebase, and after tracing the error, I get the following error:
Error Domain=FIRAuthErrorDomain Code=17007 "The email address is
already in use by another account."
UserInfo={NSLocalizedDescription=The email address is already in use
by another account., error_name=ERROR_EMAIL_ALREADY_IN_USE}
After looking it seems to be a because that firebase user is already in use, I am not sure how to fix this. I believe it is because I never signed out the user before closing app, but not am unable to login as any of my users.
Below is my code:
#IBAction func Login(sender: AnyObject) {
let email = self._Email.text!
let password = self._Password.text!
Auth.auth().createUser(withEmail: email, password: password) { (user, error) in
if error == nil {
//successfull login
print("Successful login****************************************")
//performs a segue to the next view controller
if user!.isEmailVerified{
//if the email is verified
let vc = self.storyboard!.instantiateViewController(withIdentifier: "ProfileView") as! ProfileView
self.present(vc, animated: true, completion: nil)
}
else {
print("email is not verified")
}
} else {
print("Some login error")
}
}
}
As ZassX pointed out, you're indeed using the signUp method of the Firebase iOS SDK, which is the createUserWithEmail. Use this method instead to signIn using email and password:
Auth.auth().signIn(withEmail: email, password: password) { (user, error) in
// ...
}
More info: https://firebase.google.com/docs/auth/ios/password-auth
You can check the list of your registered users in your Firebase Authentication Dashboard (https://console.firebase.google.com)
Also, it is good to print out the error description if you're having an error object. Like so:
print(error.localizedDescription).
I'm trying to Auth users with email but my function always return nil user. it worked perfectly until I added Facebook sign in as well, I made sure that I'm logged out of my facebook user when I try to register a new user to firebase.
Please let me know if any more of my code is needed to answer this.
Auth.auth().createUser(withEmail: email, password: pass, completion: {
(user, error) in
if user != nil {
print ("registered")
self.performSegue(withIdentifier: "goToHome", sender: self)
} else {
print("Error")
}
})
Instead of if user != nil do if (error != nil) and have your success code in the else statement.
I am doing project on secured authentication....when i try to register my email id and password it is not going to next viewcontroller...when i run my code it is working well and not showing any errors but i am not getting output...here is my code
#IBAction func signInButtonTapped(_ sender: UIButton) {
// TODO: Do some form validation on the email and password
if let email = emailTextField.text, let pass = passwordTextField.text {
// Check if it's sign in or register
if isSignIn {
// Sign in the user with Firebase
FIRAuth.auth()?.signIn(withEmail: email, password: pass, completion: { (user, error) in
// Check that user isn't nil
if let u = user {
// User is found, go to home screen
self.performSegue(withIdentifier: "goToHome", sender: self)
}
else {
// Error: check error and show message
self.displayAlertMessage(messageToDisplay: "Password didn't match");
}
})
}
else {
// Register the user with Firebase
FIRAuth.auth()?.createUser(withEmail: email, password: pass, completion: { (user, error) in
// Check that user isn't nil
if let u = user {
// User is found, go to home screen
self.performSegue(withIdentifier: "goToEnroll", sender: self)
}
else {
// Error: check error and show message
}
})
}
}
Please check the connection in Storyboard, make sure that the segue name of link between Current VC -> Home VC is: "goToHome"
Check the same for Enroll VC
Check here if the idenfier is same as you have given in your story board.
Note: Please check first that the identifier you have mentioned here is same as your storyboard one.
Currently I'm working with a Firebase authentication and handled many errors like wrong username, password, empty fields etc and everything is working fine. However when I try to add a segue to the next page and use random email which is not exist in the database, Firebase auth didn't give me any errors and just pass the user to the next page. When I remove the segue and put random user it gives me an error that could not find such user which is what I'm trying to achieve with the segue. Please advise, what might be the problem?
AuthService file
func login(email: String, password: String, onComplete: Completion?) {
FIRAuth.auth()?.signIn(withEmail: email, password: password, completion: { (user, error) in
if error != nil {
self.handleFirebaseError(error: error! as NSError, onComplete: onComplete)
} else {
onComplete?(nil, user)
}
})
}
func handleFirebaseError(error: NSError, onComplete: Completion?) {
print(error.debugDescription)
if let errorCode = FIRAuthErrorCode(rawValue: error.code) {
switch (errorCode) {
case .errorCodeInvalidEmail:
onComplete?("Invalid email address", nil)
break
case .errorCodeWrongPassword:
onComplete?("Invalid password", nil)
break
case .errorCodeUserNotFound:
onComplete?("Can't find user", nil)
break
default:
onComplete?("There was a problem authentication. Try again", nil)
}
}
}
ViewController
#IBAction func loginBtnTapped(_ sender: Any) {
if let email = emailField.text, let pass = passwordField.text , (email.characters.count > 0 && pass.characters.count > 0) {
AuthService.instance.login(email: email, password: pass, onComplete: { (errMsg, data) in
guard errMsg == nil else {
self.alert(title: "Error Authentication", errMsg: errMsg!)
return
}
})
} else {
self.alert(title: "Username and password required", errMsg: "You must enter both a username and a password")
}
}
hybridcattt is correct. I'm going to add a more specific answer. When using segues, make sure it the next screen is not directly connected from the button, otherwise it will fire as soon as you tap it, regardless of the result you're waiting for.
Connect your view controller instead to the next view controller, like so:
And then add an indentifier to that segue.
Finally, when you get what you're waiting for (e.g. successful logging in), then do the performSegue.
If you are creating a segue in a storyboard, it fires immediately and opens the next view controller. Login code you have is async, and storyboard doesn't wait for it.
It is very likely that loginBtnTapped method is not even called if you have a segue configured (try adding a breakpoint there)
I am new to Firebase and have been trying to implement a "Sign Up" page for my app. Currently, I am only using the email feature, just to test things out. I am able to create the new user and store it in the "Login & Auth" tab in the dashboard, but for what ever reason I cannot retrieve the UID. The only way is if I close out of my app and reload it, then it can access the UID. Any suggestions on why this is?
Swift 4.1 FireBase User Create/Login Steps:-
STEP 1:- Register new firebase authentication Pod in to your Podfile :
pod 'Firebase/Auth'
STEP 2:- Open terminal and install pod with your related project directory path:
pod install
STEP 3:- import firebase authentication library in your UIViewController where ever you want:
import FirebaseAuth
STEP 4:- On your Registration UIButton Action write this snippet :
Auth.auth().createUser(withEmail: (txtEmail.text ?? ""), password: (txtPass.text ?? "")) { (result, error) in
if let _eror = error {
//something bad happning
print(_eror.localizedDescription )
}else{
//user registered successfully
print(result)
}
}
STEP 5:- If you want to Sign In after Registration use this snippet on your Sign in UIButton:
Auth.auth().signIn(withEmail: (txtEmail.text ?? ""), password: (txtPass.text ?? "")) { (result, error) in
if let _eror = error{
print(_eror.localizedDescription)
}else{
if let _res = result{
print(_res)
}
}
}
Happy Codding ;)!!!!
Example of how to create users:
Auth.auth().createUser(withEmail: email, password: password, completion: { (result, error) -> Void in
if (error == nil) {
UserDefaults.standardUserDefaults().setValue(result.uid, forKey: "uid")
print("Account created :)")
let userDict = ["Name": name!, "Major": major!, "Email": email!]
let uid = result!.uid
self.dismissViewControllerAnimated(true, completion: nil)
}
else{
print(error)
}
})
Hope this helps.
Creating user in Firebase is very easy, just add firebase to your project using cocoa pods and then create a signup screen. You need email and password. Now first import Firebase
import Firebase
Then inside on viewDidLoad() method configure firebase
FIRApp.configure()
Now get email and password from textfields and use the following code for registration.
FIRAuth.auth()?.createUserWithEmail(email!, password: password!, completion: { (user: FIRUser?, error) in
if error == nil {
//registration successful
}else{
//registration failure
}
})
Thats it.
Source: Firebase Swift Tutorial
Before you try any code, make sure your password is at least 6 characters long. Print the error if is possible, I would print the error on each function. sign up and sign in just to keep track of what you are doing.
#IBAction func signUp(_ sender: Any) {
Auth.auth().createUser(withEmail: self.usernameTextField.text!, password: self.passwordTextField.text!) {(user, error) in
if user != nil {
print("User Has SignUp")
}
if error != nil {
print(":(",error)
}
}
Auth.auth().signIn(withEmail: self.usernameTextField.text!, password: self.passwordTextField.text!) {(user, error) in
if user != nil {
print("User Has Sign In")
}
if error != nil {
print(":(",error)
}
}