Member preview

How to build Login and Sign Up functionality for your iOS app using Firebase within 15 mins

Any application built is ultimately for the users and one important aspect of developing an iOS app is to give the user the best possible personalized experience. For this purpose, we need to allow the users to sign up and login in our iOS app. In this article, we will build that functionality using Firebase in our iOS app.

App Screenshot

What is Firebase?

Firebase is a one stop shop for all service requirements of a mobile app. The more you learn Firebase, the better your app will be.

Firebase helps you build better mobile apps and grow your business” — As said by Google, it provides us with multiple services like authentication, storage, database, analytics for our app, testing, etc. For an iOS app Login Screen, we will be using the authentication services of Firebase.

Firebase Authentication is used to verify the user identity and provide them with a personalized experience. The authentication with Firebase can happen using email password, phone number or using the identity provided by the third party like Google, Facebook, Twitter and Github.

Initial setup in Xcode:

Create an Xcode project using single view app template. Let us create 4 view controllers:

  • StartViewController — first page of the app.
  • LoginViewController — the login screen.
  • SignUpViewController — the sign up screen.
  • HomeViewController — the page to go after the user logged in.

Make sure you link respective view controllers in Interface Builder(IB) from the Storyboard.

Once you create the 4 view controllers, do the following:

  • Embed the StartViewController with a NavigationController.
  • Add sign up/login buttons and text fields in your own style, similar to the ones shown in the below image. Connect the text fields and buttons in LoginViewController and SignUpViewController to respective swift files.
  • Create the following 5 segues — StartViewController to LoginViewController, StartViewController to SignupViewController and from StartViewController, LoginViewController, SignUpViewController to HomeViewController. You can refer to the arrows in the Storyboard below.
Interface Builder Setup

Firebase Setup:

  • Open Firebase console.
  • Create a project “AwesomeProject” and to add your iOS app, click on “Add Firebase to your iOS app”. Then follow the given instructions.
Should be like this
  • In the last step, you will be asked to add code into your Xcode project’s App Delegate. Click Finish. Your AppDelegate should look like:
import UIKit
import Firebase
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
FirebaseApp.configure()
return true
}
...

Firebase Authentication Setup:

Podfile
  • Open the Podfile in your project folder and add pod ‘Firebase/Auth’. You should have added pod 'Firebase/Core' in the previous step.
  • In the terminal, run $pod install in the project directory.
  • Open the SignUpViewController. Connect the textfields from IB under the name email, passwordand passwordConfirm if you haven’t done so already.
  • Add an action function signUpAction for performing signup. Add below code to the signUpAction()
@IBOutlet weak var email: UITextField!
@IBOutlet weak var password: UITextField!
@IBOutlet weak var passwordConfirm: UITextField!
...
@IBAction func signUpAction(_ sender: Any) {
if password.text != passwordConfirm.text {
let alertController = UIAlertController(title: "Password Incorrect", message: "Please re-type password", preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)

alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
else{
Auth.auth().createUser(withEmail: email.text!, password: password.text!){ (user, error) in
 if error == nil {
self.performSegue(withIdentifier: "signupToHome", sender: self)
}
else{
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)

alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}
}
}

Let’s take a minute to understand what is happening here.

  • In the if condition, we make sure that the provided password and re-typed password is the same. If not, we provide the user with an alert saying “Password Incorrect”.
  • If both are equal, then we go ahead and store data in firebase. The code below indicates the Firebase to create a user with the email and password from the text field. If there occurs an error, we provide the user with an alert else we perform segue to the HomeViewController with the identifier “signupToHome” which we setup earlier.
Auth.auth().createUser(withEmail: email.text!, password: password.text!){ (user, error) in
...
}
  • Similarly, in LoginViewController, add the following code to the loginAction() function.
@IBAction func loginAction(_ sender: Any) {

Auth.auth().signIn(withEmail: email.text!, password: password.text!) { (user, error) in
if error == nil{
self.performSegue(withIdentifier: "loginToHome", sender: self)
}
else{
let alertController = UIAlertController(title: "Error", message: error?.localizedDescription, preferredStyle: .alert)
let defaultAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)

alertController.addAction(defaultAction)
self.present(alertController, animated: true, completion: nil)
}
}

}
  • The Firebase method used is .signIn(withEmail: email, password: password) to make the user sign-in with the credentials used during their sign-up.
  • Finally, open Firebase console. Under Authentication tab, click on SIGN-IN METHOD and enable Email/Password option.
  • Let’s run the app now to test whether sign-up works.
  • Now refresh Firebase and under Users, you will see the account with which you have signed up.
  • Notice that every time you run the app, you are prompted to enter credentials. Lets make the final addition to the code so the app remembers user.
  • Go to your StartViewController, and add the code below. Auth.auth().currentUser property is used to retrieve the current user logged in with the system.
override func viewDidAppear(_ animated: Bool){
super.viewDidAppear(animated)
if Auth.auth().currentUser != nil {
self.performSegue(withIdentifier: "alreadyLoggedIn", sender: nil)
}
}
  • To logout of the app, I have added a button in HomeViewController. To this button’s action, add the following code to logout and set the ViewController to its root.
@IBAction func logOutAction(_ sender: Any) {
do {
try Auth.auth().signOut()
}
catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}

let storyboard = UIStoryboard(name: "Main", bundle: nil)
let initial = storyboard.instantiateInitialViewController()
UIApplication.shared.keyWindow?.rootViewController = initial
}
  • We are done. :) Run the app.

Note: HomeViewController of this project is a camera which I created in my previous tutorial. You could just go for a plain ViewController with just a button for LogOut.

The full project is available via GitHub link mentioned below.


I welcome all feedback and suggestions. If interested in more tutorials, comment the topics of interest and I can write specific tutorials. Happy coding.. :)