Facebook Login Integration In iOS Using Swift

Hi, In this post, we'll learn how to implement Facebook Login in iOS apps. Nowadays, users don't want to waste their time for signing up, instead they just want a quick and secure signup/login process through their social accounts. So, in this post, we'll cover how to enable Facebook login in iOS applications. Its pretty simple and easy to learn. I hope you'll enjoy it!
So, again, we'll accomplish our goal by following a step by step approach as mentioned below:
  1. Setup Xcode Project
  2. Install Facebook Pods
  3. Create App On Facebook Developer Console
  4. Write Some Code
  5. Run Your App
STEP 1: Setup Xcode Project

First of all, open your Xcode project and create a single view application. Give some name to your project and click Next.


Once you're in your project environment, drag and drop a button on your storyboard and give it some name like "Login With Facebook". Add some constraint on this button and create its action in your ViewController.swift file. After this close your Xcode project, it's time to move on step 2.

STEP 2: Install Facebook Pods

For installing Facebook pods into your project, open up the terminal and go to your project directory by giving following command in the terminal:

cd <path of your project> 

Example: cd /users/Bhanu/Desktop/Projects/FacebookDemoApp

After giving this command, you need to give one more command

pod init

This command will create a pod file in your project folder. In this file, you need to write:

    pod 'FacebookCore'
    pod 'FacebookLogin'
    pod 'FacebookShare'

After saving, your file will look like this:


Now, run this command in your terminal:

pod install

This is going to take some time to install the required facebook pods in your project. So, wait for some time. Once pods got installed, your terminal screen will look like this:


Once all this setup is done, close the terminal and go to your projects folder. Reopen your project and make sure to open .xcworkspace this time instead of .xcodeproj

STEP 3: Create App On Facebook Developer Console

In this step, we'll create our Facebook app on Facebook's developer console. So, just open your browser and go to this link: https://developers.facebook.com/docs/ios/

Here just follow the simple steps and register your new app on Facebook developer Console. I hope you know it well, and you can do it by yourself.


After creating your app and following all the steps, don't forget to add below provided XML code in your app's info.plist file in the Xcode. For this, just click on your info.plist file and select Open as a Source Code. Now, just before the </dict> tag, insert the following XML snippet into it:

    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>fb{your-app-id}</string>
            </array>
        </dict>
    </array>
    <key>FacebookAppID</key>
    <string>{your-app-id}</string>
    <key>FacebookDisplayName</key>
    <string>{your-app-name}</string>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>fbapi</string>
        <string>fb-messenger-api</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
    </array>
    <key>NSPhotoLibraryUsageDescription</key>

    <string>{human-readable reason for photo access}</string>

Here, replace {your-app-name} with your Facebook App ID. And also replace {your-app-name} with your app's display name that you specified in your App Dashboard.

STEP 4: Write Some Code

In this step, first of all, open your AppDelegate.swift file and import FBSDKLoginKit

import FBSDKLoginKit

Now, add following lines in its first application function i.e.

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        
        return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)

    }

Now under applicationWillResignActive() method, add following code and then add one more function in your AppDelegate.swift file as shown below:

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

    }

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

    }

Once all this done, let's jump over to the ViewController.swift file.

Here, first import FBSDKLoginKit and also create a dictionary as shown below:

import UIKit
import FBSDKLoginKit

class ViewController: UIViewController {
    
    var dict : [String : AnyObject]!

    override func viewDidLoad() {
        super.viewDidLoad()
    }
}

Now, under your loginBtn() method, add following lines of code:

    @IBAction func loginBtn(_ sender: Any) {
        let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
        fbLoginManager.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()
                        fbLoginManager.logOut()
                    }
                }
            }
        }
    }

    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)
                }
            })
        }

    }

Also, before the final step, don't forget to enable Keychain Sharing capabilities under your project targets:

Go to your project targets
>Capabilities
>Keychain Sharing
>Switch on the toggle button


STEP 5: Run Your App

You can now run your app and after successful login with Facebook, following data response will be printed in your console.


You can now use these details in your iOS app as per your own requirements. I hope this post may help you, somehow!

Here’s the full code for your reference:


If you've any doubts or need any further help, then do message me in the comments section below and I'll try to respond you as soon as possible.

If this tutorial helped you or you really liked it, BRING ME A COFFEE ☕️

Thanks for your time and keep coding.. 👨‍💻

Comments

Popular posts from this blog

PayPal Integration In iOS Applications | Payment Gateways iOS/Swift

How To Parse JSON Data In iOS (Swift 3 + Xcode 8) ?

UI Date Picker For UI Text Field With UI Tool Bar (Swift 3 + Xcode 8)