Go Top

Firebase Authentication – Simple Signin with Email and Password for iOS using Swift

Email and Password – The Simple Log In

One of the most useful features in Firebase Authentication is the ability create a secure user account with the user’s own email and password.  Utilizing Firebase’s secure methods is very simple and powerful and available cross platform.  Follow along in this article to learn how to tackle simple sign in for Firebase Authentication based on a user’s email and password for iOS using Swift. To learn how to setup simple sign in for Android please read my article Firebase Authentication – Simple Signin With Email and Password for Android and look for my article on how to sign in with email and password for the Web please to be posted very soon.

I admittedly believe The Setup section is a bit dry, but if you can make it through till the Manage section I believe you’ll be a bit more entertained.

 

The Setup

The setup is fairly quick and painless in Swift (as most things are) so we’ll move through the steps as quick as possible and then move on to the Manage section to get the complete picture of what you can do with Email and Password signin in Firebase Authentication for Swift.

iOS/Swift

  1.  First, you will need to create a Firebase project in the Firebase Console or import an existing project into the Firebase Console.
  2. Click Add Firebase to your iOS app, you’ll need to provide your iOS bundle ID and your App Store ID.  Even though these values state they are optional, for sign in to work correctly you must provide these values.
  3. Download the GoogleService-Info.plist file and save it in your root of your XCode project and add it to all targets.
  4. Install the pod by opening a terminal window and navigating to your project.
    1. Create a pod file if you don’t have it.
      pod init
    2. Open your podfile and add –
      pod 'Firebase/Core'
    3. Save the file and run –
      pod install
  5. Add the Initialization code to your main AppDelegate class
    import UIKit
    import Firebase
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
      var window: UIWindow?
    
      func application(application: UIApplication,
        didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?)
        -> Bool {
        FIRApp.configure()
        return true
      }
    }
  6. Enable Email and Password sign in in the Firebase Console, navigate to Auth – Sign In Method and click Email and Password, enable and click Save.

Whew, we made it! Setup Complete.  Now let’s get on with it.

Create a User’s Account

Now that we’re all setup we can get started. The first thing to do is create a user’s account in our app, you will be amazed at how simple this actually is to accomplish.

In your apps sign-in activity import Firebase.  Configure a shared instance of the FIRApp in the application:didFinishLaunchingWithOptions method.

import Firebase

func application(_ application: UIApplication, didFinishLaunchingWithOptions
      launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
  FIRApp.configure()
  return true
}

Now that we have Firebase added and configured in our class, now we can create the user’s account now with their email address and password.  I created a function called createUserAccount and convert my emailField and passwordField to text values, then call FIRAuth.auth().createUser().

@IBAction func createUserAccount(_ sender: AnyObject) {
    guard let email = emailField.text, let password = passwordField.text else { return }
    FIRAuth.auth()?.createUser(withEmail: email, password: password) { (user, error) in
      if let error = error {
        print(error.localizedDescription)
        return
      }
    }
  }

 Sign In with Email and Password

In the last section we created the user’s account and we can sign into the account now.  I’ve created a method called signInWithEmail and again I convert my emailField and passwordField to text values and this time I call FIRApp.auth().signIn().  If there is an error I’ll print that and display to the user, otherwise the user is now signed in with their own email and password.

@IBAction func signInWithEmail(_ sender: AnyObject) {
    // Sign In with user's credentials.
    guard let email = emailField.text, let password = passwordField.text else { return }
    FIRAuth.auth()?.signIn(withEmail: email, password: password) { (user, error) in
      if let error = error {
        print(error.localizedDescription)
        return
      }
    }
  }

That was easy huh! Now, let’s get ready for some fun as we manage our user’s account.

Manage Users

After you have created a user with email and password and then successfully signed the user into your app, you can perform many actions with their user information.  You can get the current user, get the user’s profile information (which may include a photo, email address or name), update the user’s profile information, reset passwords, etc.  As we continue we’ll discuss how to perform each of these and other tasks, and we’ll be doing this with our boy Bob.  Bob is a recent college grad who’s finally landed a job and is trying to clean up his act a bit from his hard partying days at college.

Get the Currently Signed in User

We’ll start by getting Bob’s user ID,  the currently signed in user, and we’ll build from there.  We’ll simply call FIRAuth.auth().currentUser() and set it equal to a constant called user.

if let user = FIRAuth.auth()?.currentUser {
      NSLog("user ="+"\(user)")
    }

 Get the User’s Profile Information

After we have the a valid Firebase User we an dig deeper and get additional data elements such as photo, email and name.  Assume we were able to get currentUser() successfully we can simply request to get the user name ( user.displayName ), user’s email ( user.email ), and get user’s photo url ( user.photoURL ).

if let user = FIRAuth.auth()?.currentUser {
  let userName = user.displayName
  let userEmail = user.email
  let userPhotoUrl = user.photoURL
  let uid = user.uid;  
}

Update a User’s Profile Information

We are able to make some simple changes to Bob’s profile, we can change the Bob’s display name and his photo url.  To accomplish this we’ll create a changeRequest by calling user.profileChangeRequest() which allows us to change the displayName(String) and change the photoURL(Uri) and then call changeRequest.commitChangesWithCompletion.  With that we’ve updated Bob’s name and photoURL associated with his user id.

let user = FIRAuth.auth()?.currentUser
if let user = user {
  let changeRequest = user.profileChangeRequest()

  changeRequest.displayName = "Bob Smith"
  changeRequest.photoURL =
      NSURL(string: "https://mysocialmedia.com/user/bob_in_a_suit_not_drunk.jpg")
  changeRequest.commitChangesWithCompletion { error in
    if let error = error {
      // An error occured.
    } else {
      // Profile successfully updated.
    }
  }
}

Change a User’s Email Address

So your user has registered with their favorite email address they have deceided that superSeXy18@yahoo.com is not very professional (no idea if that’s a real email address) and they want to update their email address to something more corporate like bob_smith_cpa@gmail.com, well fortunately with Firebase this is pretty easy to accomplish.  If the user’s credential is too old you may be required to re-authenticate, make sure you read the Re-Authenticate a User section below.

let user = FIRAuth.auth()?.currentUser

user?.updateEmail("bob_smith_cpa@gmail.com") { error in
  if let error = error {
    // An error happened.
  } else {
    // Email updated.
  }
}

 Send a User an Email to Reset Their Password

So now Bob Smith looks professional to all his new buddies at E-Corp, but he forgot his password (probably too busy trying to find a way to convert the masses to E-Coin).  Fortunately you can help him out (don’t expect the favor to be returned) and send him an email to reset his password.

To send Bob his password email you will need to get an instance of the FirebaseAuth (don’t you have this already?) and then get the email address that the account is registered to, I would have Bob enter this via an EditText field.  Once you have the string version of Bob’s email then you will call FIRAuth.auth.sendPasswordResetWithEmail(emailAddress) as shown below.  If everything is successful then Bob should get an email allowing him to reset his password.  Keep in mind that you can customize the email that is sent to your user’s by visiting the Firebase Console on the Email Templates page.

let email = "bob_smith@gmail.com"

FIRAuth.auth()?.sendPasswordResetWithEmail(email) { error in
  if let error = error {
    // An error happened.
  } else {
    // Password reset email sent.
  }
}

 

Update a User’s Password

Since Bob is too busy to check his email and probably only uses Slack (#zeroinbox), we can allow him to update his password right in the app.  Allow Bob to enter a new password (security verification is left up to you and I encourage you to set a minimum length, special characters, upper and lower case rules) as a String.  Most likely you’ll do this via an EditText so don’t forget to get the string value.  Call FIRAuth.auth().updatePassword() and pass in the string value for the new password.  If you allow Bob to set a password that is less than 6 characters you can expect to get a FirebaseAuthWeakPasswordException and no one wants that.  If the user’s credential is too old you may be required to re-authenticate, make sure you read the Re-Authenticate a User section below.

let user = FIRAuth.auth()?.currentUser
let newPassword = "aRea11yh$8dpASsWd"

user?.updatePassword(newPassword) { error in
  if let error = error {
    // An error occured.
  } else {
    // Password changed.
  }
}

Delete a User’s Account

The time may come when Bob is too swamped at E-Corp to keep using your app as it’s distracting him from his climp up the evil ladder and Bob just wants to delete his account.  Never fear Bob, we can’s save you from selling your soul but we can delete your account from our awesome app.  As long as you have a reference to the currentUser you can call FIRAuth.auth().deleteWithCompletion() and Bob’s account is no more.  Simple.  If the user’s credential is too old you may be required to re-authenticate, make sure you read the Re-Authenticate a User section below.

let user = FIRAuth.auth()?.currentUser

user?.deleteWithCompletion { error in
  if let error = error {
    // An error occured.
  } else {
    // User account deleted.
  }
}

Re-Authenticate a User

If it’s been some time since Bob signed in (forget that whole account deletion section above, Bob couldn’t go through with deleting his account) you may need to re-authenticate a user for several of the actions above – Delete a User’s Account, Updating a User’s Password, Change a User’s Email Address.  If you try one of these actions and receive a FIRAuthErrorCodeCredentialTooOld error then you will need to Re-Authenticate your user and get new signin credentials.  To do this you will basically have the user sign in to their app but this time you’ll use a different method.  Get a new instance of FIRAuth.currentUser.  Create a new FIRAuthCredential and set it equal to FIRAuthCredential.credentialWithEmail:password(email, password), you’ll need to pass in email and password as text values.  Next call FIRAuth.auth().reauthenticateWtihCredential() and pass in the FIRAuthCredential, if successful the user is re-authenticated and you can retry the original action.  If you receive an error then you may listen for that and deal with it as appropriate.

let user = FIRAuth.auth()?.currentUser
var credential: FIRAuthCredential

// Prompt the user to re-provide their sign-in credentials and insert into the below line
credential.credentialWithEmail:password("bob_smith@gmail.com", "somethinghard")

user?.reauthenticateWithCredential(credential) { error in
  if let error = error {
    // An error happened.
  } else {
    // User re-authenticated.
  }
}

 Sign a User Out

Now after all that work don’t forget to give Bob a way to sign out of your app, after all he’s got work to do!

try! FIRAuth.auth()!.signOut()

 

That’s all folks!  Thanks for reading this to the end, I hope it wasn’t too boring for you.  The Firebase Docs have everything you’ve read here documented, but without my amazing commentary, they are excellent and I encourage you to check them out.

As I mentioned in the beginning I’ve posted Firebase Authentication – Simple Signin With Email and Password for Android and look for my article on how to sign in with email and password for the Web to be posted very soon.  Please check back for those and if you enjoyed this please share it on social media.  If you have found any errors or omissions please leave me feedback so I can get it corrected as soon as possible!

 

    3 COMMENTS

  • Giri Prasad Poonati
    / Reply

    Heyy I am new to FireBase and even to swift , so please intimate me for your upcoming articles on FireBase and Swift . And please post the next articles of Firebase soon.

  • Dusan
    / Reply

    Hi, I see that you are well-versed with firebase, so you might know the answer I can’t seem to find anywhere. When I create a user, I want to include his name in the verification email that is sent to confirm registration. By default it is set as %DISPLAY_NAME% placeholder in the outgoing email, but I can’t figure out how to change that for user’s actual name, so the verification mail would be more personalized. Thanks in advance.

    • marty331
      / Reply

      Dusan,
      You should be able to do this easily.
      let user = FIRAuth.auth()?.currentUser
      let username = user?.displayName

      Hope that helps!

Leave a Reply

Your email address will not be published. Required fields are marked *