iOS Facebook and Gmail SignIn/Login and Save ID’s in Firebase (Swift 5 ).

sunny
7 min readNov 2, 2020

--

FaceBook Sign In

Follow the Below steps for Facebook login using Facebook SDK. And save that information in FireBase.

Step 1: Add your app on Facebook for developers website

Go to https://developers.facebook.com/ and create a new App from the left corner of the page

Facebook Create New App Page

Step 2: Install dependencies using Swift Package/ Cocoapods

Using Swift Package(It’s same as mentioned in Facebook Development Site)

Final Swift Package Setup look like below.

By Using Cocoapods

After adding your app, install necessary dependencies into your app via Cocoapods just like you do for any other libraries. You can follow the instruction here.

Note:
You just need those two dependencies for the login purpose. Go to this page for more details.

pod ‘FBSDKCoreKit’
pod ‘FBSDKLoginKit’

Step 3: Enable Facebook login on Firebase

You also register your app on Firebase. Login to Firebase Console and create a new project. Then go to Authentication -> SIGN-IN METHOD from the navigation bar and enable Facebook. You’ll need ‘Facebook App ID’ and ‘App Secret’. You can find those keys on your project page on ‘Facebook for developers’ websites (Setting -> Basics from the navigation bar).

You will need ‘OAuth redirect URI’ located at the bottom of the pop-up. Copy and keep it since you also need to paste it on your Facebook app page later.

Firebase project site

Step 4: Configure your app on Facebook

Select on the PRODUCTS menu located at the bottom of the navigation. You will see thumbnails of the services that Facebook provides. Click the ‘Set up’ button on the ‘Facebook Login’ thumbnail. Then you will be asked which platform to use, so just select iOS. Once you did the Facebook login setup this will display like below. I Selected Analytics and Facebook login based on your preference you can select whichever you want means if you need just login select that alone and ignore Analytics.

On Facebook developer site

4–1. Set up Your Development Environment

You can skip this part since we have already installed the pods/ swift package.

4–2. Configure Your info.plist

Add an XML snippet to ‘info.plist’ to configure the information, The XML snippet looks something like this.

<dict>
<array>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string></string>
<key>CFBundleURLSchemes</key>
<array>
<string>fbxxxxxx</string>
</array>
</dict>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string></string>
<key>CFBundleURLSchemes</key>
<array/>
</dict>
<dict>
<key>CFBundleTypeRole</key>
<string>Editor</string>
<key>CFBundleURLName</key>
<string></string>
<key>CFBundleURLSchemes</key>
<array/>
</dict>
</array>
<key>FacebookAppID</key>
<string>xxxxx</string>
<key>FacebookAutoLogAppEventsEnabled</key>
<false/>
<key>FacebookDisplayName</key>
<string>abc</string>
<key>NSAppTransportSecurity</key>
<dict>
<key>NSExceptionDomains</key>
<dict>
<key>facebook.com</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<key>fbcdn.net</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<key>akamaihd.net</key>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
<dict>
<key>NSIncludesSubdomains</key>
<true/>
<key>NSThirdPartyExceptionAllowsInsecureHTTPLoads</key>
<true/>
<key>NSThirdPartyExceptionRequiresForwardSecrecy</key>
<false/>
</dict>
</dict>
</dict>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fbapi20130214</string>
<string>fbapi20130410</string>
<string>fbapi20130702</string>
<string>fbapi20131010</string>
<string>fbapi20131219</string>
<string>fbapi20140410</string>
<string>fbapi20140116</string>
<string>fbapi20150313</string>
<string>fbapi20150629</string>
<string>fbapi20160328</string>
<string>fbauth</string>
<string>fb-messenger-share-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
</dict>
</plist>

4–3. Add URL Types

Add Facebook App ID in schema( Target->Info)

Now the setup is done, let’s jump into code.

4–4. Connect App Delegate

At this point, you need to add the code to connect your app with Facebook SDK or just add the following code to your ‘AppDelegate.swift’ file. And I am not using a storyboard or swift UI that’s why it’s looks a little different from my App delegate.

import UIKit
import FBSDKCoreKit
@mainclass AppDelegate: UIResponder, UIApplicationDelegate {var window: UIWindow?func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {//FBApplicationDelegate.shared.application(application,didFinishLaunchingWithOptions: launchOptions)// Override point for customization after application launch.window = UIWindow()window?.rootViewController = SignInViewController()window?.makeKeyAndVisible()return true}func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {//FBApplicationDelegate.shared.application(app,open: url,sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,annotation: options[UIApplication.OpenURLOptionsKey.annotation])return true}}

4–5: Add the Facebook Login Button

Inside of viewDidLoad() in the ‘ViewController.swift’ file, add the following code to implement the Facebook button programmatically.And for this code and UI like below.

import FBSDKLoginKitclass ViewController: UIViewController {  override func viewDidLoad() {    super.viewDidLoad()        let loginButton = FBLoginButton()    // Optional: Place the button in the center of your view.    loginButton.center = view.center    view.addSubview(loginButton)  }}
Default Facebook SDK Button

Custom Login Button

We have one more option we can place a normal UIButton and follow the below steps for the same. And this is UIButton you can customize however we want like background color and title.

With Normal UIButton

When you log in with the services such as Google, Facebook, or Twitter, it is usual to be asked for permission. In order to request additional read permissions, you can add the code like this “ loginButton.readPermissions = [“public_profile”, “email”] ”

public func loggingWithFaceBook(with viewController: UIViewController, completion: @escaping (Error?) -> Void) {let loginManager = LoginManager()loginManager.logIn(permissions: ["public_profile", "email"], from: viewController) { [weak self] (result, error) inguard let accessToken = AccessToken.current?.tokenString else {print("Failed to get access token for Facebook")completion(error)return}let credentials = FacebookAuthProvider.credential(withAccessToken: accessToken)//following steps is for savings Facebook credentials in Fire base we can look more about this further in my tutorial.self?.fireBaseSignIn(with: credentials, completion: { (data, error) inguard let result = data, error == nil else {print("FB Login Error: \(String(describing: error?.localizedDescription))")completion(error)return}completion(nil)})}}

4–6: Add code to check the login status

If we use FireBase SDK to save Facebook credentials, then we can check by using the following code whether the user is log in earlier using Facebook for that code look like below.

private func isUserPreviouslySignInWithFB() -> Bool {if let providerData = Auth.auth().currentUser?.providerData {for userInfo in providerData {switch userInfo.providerID {case "facebook.com":self.saveUserInfo()return truedefault:print("provider is \(userInfo.providerID)")}}}return false}

4–7: Add ‘OAuth redirect URI’ to your Facebook app page

From the navigation bar, click Facebook Login on the navigation bar. Then, go to Settings. In the Settings page, find the textField for ‘Valid OAuth Redirect URIs’. And paste your ‘OAuth redirect URI’ from the Firebase Console.

That’s all for Facebook configuration, by using the above steps we can log in the user into Facebook.

For Firebase setup please follow the below steps.

Firebase Setup

Add Firebase to your app

On the Firebase Console, Create project it contains 3 steps, once done with it project is created for you. You should see the ‘Your apps’ section. Select iOS and move on to the app creation process. Basically, you just need to follow the instruction,

For Reference see the above images.

5–1: Register app

Add your app’s Bundle Identifier.

5–2: Download GoogleService-info.plist

You will download ‘GoogleService-info.plist’ file here and add it to your Xcode project.

5–3: Add Firebase SDK

Follow Step 3 Adding firebase pods to project.

pod 'Firebase/Auth', '6.33.0'

Now App is created and Firebase end setup is done for you.

And will look like below.

App is created on Firebase

5–4: Let's Jump into code

Add the following code in your AppDelegate. Don’t forget to add import Firebase at the top.

FirebaseApp.configure()

5- 5: Authenticate with Firebase

Earlier we use Facebook SDK to log in to Facebook, now using firebase we can save facebook credentials in Firebase. The code will be as below.

public func loggingWithFaceBook(with viewController: UIViewController, completion: @escaping (Error?) -> Void) {let loginManager = LoginManager()loginManager.logIn(permissions: ["public_profile", "email"], from: viewController) { [weak self] (result, error) inguard let accessToken = AccessToken.current?.tokenString else {print("Failed to get access token for Facebook")completion(error)return}let credentials = FacebookAuthProvider.credential(withAccessToken: accessToken)self?.fireBaseSignIn(with: credentials, completion: { (data, error) inguard let result = data, error == nil else {print("FB Login Error: \(String(describing: error?.localizedDescription))")completion(error)return}completion(nil)})}}
private
func fireBaseSignIn(with credentials: AuthCredential, completion: @escaping (AuthDataResult?, Error?) -> Void) {
Auth.auth().signIn(with: credentials) { (result, error) inguard let dataResult = result else {completion(nil, error)print("Firebase login error ")return}completion(dataResult, nil)}}}

Once it’s login with Facebook it will save into firebase it will look like below.

Facebook token save into firebase.

The Gmail login will be here.

With help of the following URLs, this one is written, please add in comments if you need any help on this topic. And please clap if you like this.

https://developers.facebook.com/docs/ios/

https://firebase.google.com/docs/ios/setup

--

--

No responses yet