X

Firebase Authentication Tutorial for iOS

4.9/5 - (31 votes)

Developing a custom authentication will consume a more time and you also need to manage server side coding as well you need to do spend time on testing.

So to avoid all hurdles, Firebase is providing a better authentication system which you can integrate in your application easily.

If you are don’t know about Firebase than it is a backend service provider with easier integration of sdk and ready-to-use UI Elements for user authentication. Firebase supports authentication using Email, Phone Numbers or even supports social media login using Facebook, Twitter and Google.

In this tutorial we will learn about How to authenticate users using Email, Google, and Facebook.

Google has its own documentation for Firebase Authentication in ios.

Here are the steps to integrate Firebase SdK For Authentication.

Step1:

First of all you need to create project in xcode with Single View Application. You can set the project name whatever you want and select Swift language.

Step2:

Now, you have to Setup Project in Firebase console.

For this, You have to do login in Firebase with your account. Click on Get started for Free and select add project. After that you will see Popup of Add Project as below. Add name what you want add.  Project ID will appear After adding project name.

After creating project,it will take you to Dashboard where you have to select platform to integrate firebase into your app.

After selecting iOS platform, you have to follow step by step process to add firebase in your app.

1. Register your app by adding bundle_id.

2. You will be instructed to download  GoogleService-info.plist file into your Xcode project After registeredyour  app:

 

Make sure Copy Item If needed is unchecked when you add plist file into your project.Now go back to Firebase dashboard and select continue.

3. shows you how to add Firebase sdk into your project using CocoapodsBelow are the steps to add pod in your podfile

  • Open Terminal and Create podfile in your project.
  • $ cd your-project directory
  • $ pod init
  • add below dependencies in your podfile like this:

                  pod ‘Firebase/Core’              

                  pod ‘Firebase/Auth

  • Install podfile

                 

$ pod install

After installing pods, you will see  .xcworkspace file in your project.

You have to use .xcworkspace file instead  of .xcodeproj file.

After that, get back to the firebase dashboard and click on Continue.

4. The fourth step will teach you how to implement Firebase in you app.In your project, open appdelegate.swift file and import Firebase sdk to utilize Firebase APIs.Insert below code:         

import Firebase

Initializeobject in the application:didFinishLaunchingWithOptions: method

FirebaseApp.configure()

Now in your firebase Dashboard,Click Finish button to see Project details.

Finally, You are ready to implement Firebase Authentication with Different sign In providers.

SignUp Method.

First of all In your Firebase Console Select AuthenticationSign-In Method  and Enable Email/Password option. After enable it, you can implement Sign-up functionality. In your Viewcontroller.swift file import Firebase and FirebaseAuth

import Firebase
import FirebaseAuth

Create two Textfield and link it to storyboard to enter email and password like this:

@IBOutlet weak var txtEmail:UITextField!
@IBOutlet weak var txtPassword:UITextField!

Add following code into Click event of SignUp button to create newUser

@IBAction func btnSignupClicked(_ sender: UIButton) {
//for signup new user
if ((txtEmail.text ? .isEmpty) ! || (txtPassword.text ? .isEmpty) !) {
self.showAlert(message: "All fields are mandatory!")
return
} else {
Auth.auth().createUser(withEmail: txtEmail.text!, password: txtPassword.text!) {
(authResult, error) in
// ...
if ((error == nil)) {
self.showAlert(message: "Signup Successfully!")
} else {
self.showAlert(message: (error ? .localizedDescription) !)
}
}
}
}

Note : self.showAlert(message:String) is a common fuction to call Alert.

func showAlert(message:String)
{
let alert = UIAlertController(title: message, message: "", preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true)
}

So, In if condition we check if user has filled both of the textfield, if user leave it blank then we display alert.

Below is the Form. add email-id and password to sign-up:

 

After Click on signup, User will get alert of Successfully Signup like below:

You can not sign up again with same account,otherwise Firebase returns error message.If you check in Firebase Dashboard,You will find email id in Users tab under Authentication.

Sign-in Users:

For this, add below code in Click event of Sign-in button

@IBAction func btnSignInClicked(_ sender:UIButton)
{
index = 1
Auth.auth().signIn(withEmail: txtEmail.text!, password: txtPassword.text!) { (user, error) in
// ...
if(error == nil )
{
if let user = user {
_ = user.user.displayName
let user_email = user.user.email
print(user_email!)
}
self.showAlert(message: "SignIn Successfully!")
}
else{
if let errorCode = AuthErrorCode(rawValue: error!._code) {
switch errorCode {
case.wrongPassword:
self.showAlert(message: "You entered an invalid password please try again!")
break
case.userNotFound:
Auth.auth().createUser(withEmail: self.txtEmail.text!, password: self.txtPassword.text!,
completion: { (user, error) in
if error == nil {
if let user = user {
_=user.user.displayName
let user_email = user.user.email
print(user_email!)
}else {
if let errorCode = AuthErrorCode(rawValue: error!._code) {
switch errorCode {
case .invalidEmail:
self.showAlert(message: "You entered an invalid email!")
case .userNotFound:
self.showAlert(message: "User not found")
default:
print("Creating user error 2 \(error.debugDescription)!")
self.showAlert(message: "Unexpected error \(errorCode.rawValue) please try again!")
}
}
}
self.dismiss(animated: true, completion: nil)
}
})
default:
self.showAlert(message: "Unexpected error \(errorCode.rawValue) please try again!")
print("Creating user error \(error.debugDescription)!")
}
}
}
}
}

In above code, user will sign-in with their email and password using  Auth.auth().signIn(withEmail: txtEmail.text!, password: txtPassword.text!) { (user, error) in {} these function.

If there is any error to sign-in then it will call else method. If user will enter wrong password then alert of invalid password will appear. if there is no user find then it will call createUser Method for signup.

Sign-Out Users:

Call Signout API of Firebase on Click event of log-out button.

@IBAction func  btnLogoutClicked(_ sender: AnyObject)
{
print(index)
if(index == 1)
{
//Email
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
self.showAlert(message: "SignOut Successfully!")
}catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
self.showAlert(message: signOutError.localizedDescription)
}
}
}

Next we are going implement Facebook Login using Firebase Authentication

Facebook Login:

First of all Create an app on Facebook for Developers page.

Now go to the  Firebase console  and enable Facebook in Sign-In Method tab  under Authentication section. add your App Id and App Secret of facebook app in it. Copy OAuth redirect URI and paste it into Facebook app’s settings page on the Facebook for Developers site in the Products > Facebook Login > Settings config.

After Configuration ,  add  pod ‘FBSDKLoginKit in your xcode project using Cocoapods.

You already created podfile earlier. So there is no need to repeat that steps again. But you have to add pod for facebook.  

1. Add  pod ‘FBSDKLoginKitin your podfile.

2. Open Terminal add $ cd your-project directory

3. Run  pod update  command.

4. Integrate Facebook Login into your app. You can also follow developer’s documentation for facebook integration or follow below Steps.

You have to Set Up Facebook Login kit from  Add a Product tab under Dashboard section of facebook.

Click on Set Up button and it will directly add in Product section of facebook dashboard.

5. Add your app’s  Bundle Id into Settings > Basic tab  to register your app in Facebook

6. Enable Single Sign On for your app.

7. Configure your info.plist file by adding following code.

  •     Right-click info.plist, and choose Open As Source Code.
  •    Copy and paste the following XML snippet into the body of your file (    <dict>…</dict>).

             <key>CFBundleURLTypes</key>

                   <key>CFBundleURLTypes</key>
                   <array>
                          <dict>
                          <key>CFBundleURLSchemes</key>
                          <array>
                                 <string>fb181750629382598</string>
                          </array>
                          </dict>
                   </array>
                   <key>FacebookAppID</key>
                   <string>181750629382598</string>
                  <key>FacebookDisplayName</key>
                  <string>Firebase Login Demo</string>

  • Also add following code into info.plist file to use any of Facabook dialogue in app.

                   <key>LSApplicationQueriesSchemes</key>
                   <array>
                         <string>fbapi</string>
                         <string>fb-messenger-share-api</string>
                         <string>fbauth2</string>
                         <string>fbshareextension</string>
                   </array>

8. Initialize Facebook SDK into AppDelegate.swift file.      

import FBSDKCoreKit

Add following code into application: didFinishLaunchingWithOptions: method FBSDKApplicationDelegate.sharedInstance().application(application,didFinishLaunchingWithOptions: launchOptions)

9. If you are using iOS 9 or above then add below method in AppDelegate.Swift

func application(_ app: UIApplication, open url: URL, options:
[UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
let handled:Bool = FBSDKApplicationDelegate.sharedInstance()
.application(app, open: url, sourceApplication: options
[.sourceApplication] as? String, annotation: options[.annotation])
print("handle",handled)
return handled
}

If you are using older version of iOS SDK then add below code:

func application(_ application: UIApplication, open url: URL,
sourceApplication: String?, annotation: Any) -> Bool {
let handled = FBSDKApplicationDelegate.sharedInstance().
application(application, open: url, sourceApplication: sourceApplication,
annotation: annotation)
return handled
}

10. Add Facebook Login in ViewController.swift file

import FBSDKCoreKit
import FBSDKLoginKit

In this tutorial we used Custom Social Buttons for Soical Login.

For Facebook Login add button into storyboard and link its Click event into ViewController.swift file.

11. add Following code into AppDelegate.swift file

func applicationWillResignActive(_ application: UIApplication) {
FBSDKAppEvents.activateApp()
}

Declare let loginManager:FBSDKLoginManager = FBSDKLoginManager()  and var dict : [String : AnyObject]! on top in your ViewController. so you can use FBSDKLoginManager in FBLogin Event. To store users detail declare object of dictionary.
12. And add below code into Click event of custom facebook login button:

@IBAction func FBSignInButtonClicked(_ sender: AnyObject) {
index = 3
loginManager.logIn(withReadPermissions: ["email"], from: self) { (result, error) in
if (error == nil)
{
let fbloginresult : FBSDKLoginManagerLoginResult = result!
if fbloginresult.grantedPermissions != nil {
if(fbloginresult.grantedPermissions.contains("email "))
{
self.getFBUserData()
}
}
}
}
}
func getFBUserData(){
if((FBSDKAccessToken.current()) != nil){
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name,
first_name, last_name, picture.type(large), email"]).start
(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
self.dict = result as! [String : AnyObject]
print(result!)
print(self.dict)
}
})
}
}

In getFBUserData() function, we use graph request to get email-id and other details of user. To logout user from facebook, use FBSDKLoginManager() like below:

Note: We Already declare object of  FBSDKLoginManager() on top of the code.

So, add following code in Click event of Logout button.

if FBSDKAccessToken.current() != nil {
loginManager.logOut()
}
self.showAlert(message: "SignOut Successfully!")

So,below is the output of our code for Facebook Login.

When user tap on custom facebook login button, popup of Sign-up in facebook will appear.

So,below is the output of our code for Facebook Login.

When user tap on custom facebook login button, popup of Sign-up in facebook will appear.

After click on Continue, You will be able to sign-in in facebook successfully as below image

So,Here  We added facebook login in our app successfully.

Now We are going to implement  Google Sign-in in our app.

Google Sign-in:

In Firebase console  enable Google in Sign-In Method tab under Authentication section. add Email-id in Project support email tab. Add Web client ID and Web client secret from  Google API Console by Selecting your project in it and save it. Follow below steps to implement Google Sign-In.

1. add  pod ‘GoogleSignIn’ in podfile of your project.( Note:Steps to create podfile discussed earlier  )

2. Open Terminal add $ cd your-project directory

3. Run  pod update  command.

4. Initialize  Google Sign-In in AppDelegate.swift file.

import GoogleSignIn 

5. Add custom URL schema in your project.

    1. Select your app from Target section then select info tab. Expand URL Types.

    2. CopyREVERSED_CLIENT_ID from GoogleService-Info.plist and add it into URL
  schema box. Keep other fields blank. Your URL Types will look like following image.

6. Configure  Google sign-in  in application:didFinishLaunchingWithOptions: method.

       GIDSignIn.sharedInstance().clientID = FirebaseApp.app()?.options.clientID

7. Call handleURL method of GIDSignIn in application:openURL:options: in AppDelegate if you are using iOS 9 or above.

func application(_ app: UIApplication, open url: URL, options: 
[UIApplicationOpenURLOptionsKey :Any] = [:]) -> Bool {
if( url.absoluteString.contains("fb"))
{
return GIDSignIn.sharedInstance().handle(url, sourceApplication:
options[UIApplicationOpenURLOptionsKey.sourceApplication] as?
String, annotation: [:])
}

If you are using  iOS 8 and older version then add following method in your AppDeleate.

func application(_ application: UIApplication, open url: 
URL, sourceApplication: String?, annotation: Any) -> Bool {
GIDSignIn.sharedInstance().handle(url, sourceApplication: 
sourceApplication, annotation:    annotation)
{
return true
}
}

8. Open Viewcontroller.swift file to implement login functionality. Import GoogleSignIn.

import GoogleSignIn

9. Declare GIDSignInDelegate and GIDSignInUIDelegate protocol like below.

              class ViewController: UIViewController,GIDSignInUIDelegate,GIDSignInDelegate

10. Add UIButton in storyboard and link it’s click event into ViewController.swift file.

11. Set up delegate object of  GIDSignIn and UI delegate of GIDSignInUIDelegate in ViewDidLoad() method.

           GIDSignIn.sharedInstance().uiDelegate = self

            GIDSignIn.sharedInstance().delegate = self

12. Here we used custom button, so add following code of sign-in using google account in Click event of Sign-in button.

@IBAction func googleSignIn(_ sender: AnyObject) {
GIDSignIn.sharedInstance().signIn()
}

13. Add GIDSignInDelegate Delegate methods to handle sign-in process

func sign(_ signIn: GIDSignIn!, didSignInFor user: GIDGoogleUser!, withError error: Error!) {
if(error != nil)
{
print(error.localizedDescription)
}
else
{
let fullName = user.profile.name
let givenName = user.profile.givenName
let familyName = user.profile.familyName
let email = user.profile.email
print("User email address is \(String(describing: email))")
}
}
func sign(_ signIn: GIDSignIn!, didDisconnectWith user: GIDGoogleUser!, withError error: Error!) {
// Perform any operations when the user disconnects from app here.
// ...
print(error.localizedDescription)
}

So, When user going to sign-in with his google account, the popup to continue sign-in process will appear like this:

When user tap on Continue button, user can sign-in with there account.see the below screenshot.

Finally Authenticate with Google Sign-in is completed.

To Logout user, add following code into Click event of  logout button:

@IBAction func  btnLogoutClicked(_ sender: AnyObject)
{
//Google
let firebaseAuth = Auth.auth()
do {
try firebaseAuth.signOut()
self.showAlert(message: "SignOut Successfully!") 
try firebaseAuth.signOut()
}catch let signOutError as NSError {
print ("Error signing out: %@", signOutError)
}
}

Conclusion:

Now I assumed that  you have idea to implement Firebase Authentication using Email,Facebook as well as via Google. Thanks to read this article.If you have any questions or doubts, Feel free to Contact us.

 

               

Dipen Patel: Leading web development and mobile app development company India.

View Comments (0)