Simplified iOS

  • Home
  • About
  • Contact
  • Advertise
  • Write for Us

Facebook Login Swift 3 Tutorial – Adding Facebook Login to iOS App

August 10, 2017 by Belal Khan 19 Comments

Hello guys, this post is about Facebook Login in Swift 3. If you want to add Facebook Login feature in your iOS Application then here is  “Facebook Login Swift 3 Tutorial” for you. In the previous post, we have also covered about Google Sign In using Swift. Now let’s learn about integrating Facebook Login.

Creating Facebook App

The very first thing we need is our Facebook App. We need our Facebook App ID to integrate Facebook Login in our iOS Application.

  • Sign in to your Facebook Account and go to Facebook Developers. And then select Add a New App. You can also choose an existing app from your account (if you have already created an app there).

creating facebook app

  • After creating the Facebook App you will get your App ID.

facebook app id

  • Now we will use this app to integrate Facebook Sign In with our iOS Application.

Facebook Login Swift 3 Tutorial

Creating Xcode Project

  • Create a new Xcode Project. I just created a project named FacebookLoginExample.
  • Now we need to add Facebook Swift SDK using CocoaPods.

The next steps are about creating and installing Pods; if you don’t familiar with it you can see my previous tutorial about Firebase iOS Tutorial where I explained about pods in every detail.

Adding Facebook SDK

  • Create a Podfile in your project and write the following code inside.
target 'FacebookLoginExample' do
  use_frameworks!
  pod 'FacebookCore'
  pod 'FacebookLogin'
end
  • Now run the command pod install in your terminal and it will install FacebookLogin SDK in your project.
  • Now close your project and open the project with the extension .xcworkspace.

Adding Facebook Sign In Button

  • To add Facebook Sign In Button open ViewController.swift and write the following code.
//
//  ViewController.swift
//  FacebookLoginExample
//
//  Created by Belal Khan on 09/08/17.
//  Copyright © 2017 Belal Khan. All rights reserved.
//

import UIKit

import FacebookLogin
import FBSDKLoginKit

class ViewController: UIViewController {

    var dict : [String : AnyObject]!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //creating button
        let loginButton = LoginButton(readPermissions: [ .publicProfile ])
        loginButton.center = view.center
        
        //adding it to view
        view.addSubview(loginButton)
        
    }
}

Making Facebook Login

  • Now come inside AppDelegate.swift and modify it as below.
//
//  AppDelegate.swift
//  FacebookLoginExample
//
//  Created by Belal Khan on 09/08/17.
//  Copyright © 2017 Belal Khan. All rights reserved.
//

import UIKit
import FBSDKLoginKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    //added these 3 methods 
    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
    }
    
    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)
    }
    
    func applicationDidEnterBackground(_ application: UIApplication) {

    }

    func applicationWillEnterForeground(_ application: UIApplication) {
    
    }

    func applicationDidBecomeActive(_ application: UIApplication) {

    }

    func applicationWillTerminate(_ application: UIApplication) {

    }


}

  • Now we will handle the login so add these two methods inside ViewController.swift.
    //when login button clicked
    @objc func loginButtonClicked() {
        let loginManager = LoginManager()
        loginManager.logIn([ .publicProfile ], viewController: self) { loginResult in
            switch loginResult {
            case .failed(let error):
                print(error)
            case .cancelled:
                print("User cancelled login.")
            case .success(let grantedPermissions, let declinedPermissions, let accessToken):
                self.getFBUserData()
            }
        }
    }
    
    //function is fetching the user data
    func getFBUserData(){
        if((FBSDKAccessToken.current()) != nil){
            FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, 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)
                }
            })
        }
    }

The Final ViewController.swift Code

  • So having all the above code your final ViewController.swift will look like this.
//
//  ViewController.swift
//  FacebookLoginExample
//
//  Created by Belal Khan on 09/08/17.
//  Copyright © 2017 Belal Khan. All rights reserved.
//

import UIKit

import FacebookLogin
import FBSDKLoginKit

class ViewController: UIViewController {

    var dict : [String : AnyObject]!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        //creating button
        let loginButton = LoginButton(readPermissions: [ .publicProfile ])
        loginButton.center = view.center
        
        //adding it to view
        view.addSubview(loginButton)
        
        //if the user is already logged in
        if let accessToken = FBSDKAccessToken.current(){
            getFBUserData()
        }
        
    }

    //when login button clicked
    @objc func loginButtonClicked() {
        let loginManager = LoginManager()
        loginManager.logIn([ .publicProfile ], viewController: self) { loginResult in
            switch loginResult {
            case .failed(let error):
                print(error)
            case .cancelled:
                print("User cancelled login.")
            case .success(let grantedPermissions, let declinedPermissions, let accessToken):
                self.getFBUserData()
            }
        }
    }
    
    //function is fetching the user data
    func getFBUserData(){
        if((FBSDKAccessToken.current()) != nil){
            FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, 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)
                }
            })
        }
    }
}

  • Now the last thing is modifying the Info.plist file.

Modifying Info.plist File

  • Now right click on the Info.plist file and open it as source code. And just before the closing </dict> tag add the following code.
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>fb{your-app-id-here}</string>
            </array>
        </dict>
    </array>
    <key>FacebookAppID</key>
    <string>{your-app-id-here}</string>
    <key>FacebookDisplayName</key>
    <string>Simplified iOS</string>
    <key>LSApplicationQueriesSchemes</key>
    <array>
        <string>fbapi</string>
        <string>fb-messenger-api</string>
        <string>fbauth2</string>
        <string>fbshareextension</string>
    </array>
    <key>NSPhotoLibraryUsageDescription</key>
    <string>We want to get your profile picture for this app</string>
  • Make sure you put the values according to your facebook app id here. And you are ready.
  • Now run your application and login.
facebook login swift 3 tutorial

Facebook Login Swift 3 Tutorial

Facebook Login Swift 3 Tutoriall

Facebook Login Swift 3 Tutorial

So you can see we got the user data from Facebook. Now we can use this data for our app’s user profile. If you are facing any issues or problems here is my source code for you.

[sociallocker] Facebook Login Swift 3 Tutorial [/sociallocker]

Now that’s it for this Facebook Login Swift 3 Tutorial. Please don’t hesitate in leaving your comments if you need to ask something related to this Facebook Login Swift 3 Tutorial. Thank You 🙂

Share this:

  • Tweet
  • Share on Tumblr
  • WhatsApp

Related

Filed Under: iOS Advanced, iOS Development Tutorial Tagged With: facebook login swift 3 tutorial, facebook sdk swift 3

About Belal Khan

I am Belal Khan, I am currently pursuing my MCA. In this blog I write tutorials and articles related to coding, app development, iphone etc.

Comments

  1. Mark Underwood says

    August 14, 2017 at 5:50 pm

    Very easy to understand example! I have some questions…

    (1) I get 4 warnings with respect to “defined by never used” – those don’t seem to cause problems, but…
    (2) …while it seems to log in to Facebook properly, nothing is going into the console output. While new to Swift, as an old hack, I don’t see how the method “loginButtonClicked” gets called – unless it’s directly from the Facebook SDK…so if nothing’s calling that method, it would explain why I don’t get anything in the output.

    Reply
  2. George Hanna says

    August 17, 2017 at 10:26 am

    I amgetting the following errors please help
    objc[1330]: Class PLBuildVersion is implemented in both /Users/apple/Desktop/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/AssetsLibraryServices.framework/AssetsLibraryServices (0x11aedbcc0) and /Users/apple/Desktop/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator.sdk/System/Library/PrivateFrameworks/PhotoLibraryServices.framework/PhotoLibraryServices (0x11acf26f0). One of the two will be used. Which one is undefined.
    2017-08-17 13:22:44.038 FaceBook[1330:18946] Falling back to loading access token from NSUserDefaults because of simulator bug
    2017-08-17 13:22:44.040 FaceBook[1330:18946] Falling back to storing access token in NSUserDefaults because of simulator bug
    2017-08-17 13:22:44.041 FaceBook[1330:18946] Falling back to loading access token from NSUserDefaults because of simulator bug
    2017-08-17 13:22:44.041 FaceBook[1330:18946] Falling back to storing access token in NSUserDefaults because of simulator bug
    2017-08-17 13:22:44.043 FaceBook[1330:18946] Falling back to loading access token from NSUserDefaults because of simulator bug
    2017-08-17 13:22:44.043 FaceBook[1330:18946] Falling back to storing access token in NSUserDefaults because of simulator bug
    2017-08-17 13:22:44.189918+0300 FaceBook[1330:18946] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /Users/apple/Library/Developer/CoreSimulator/Devices/41E9A3A1-20CF-4B9C-9D6B-7708D21CE918/data/Containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
    2017-08-17 13:22:44.190473+0300 FaceBook[1330:18946] [MC] Reading from private effective user settings.
    2017-08-17 13:22:45.693 FaceBook[1330:18946] -canOpenURL: failed for URL: “fbauth2:/” – error: “The operation couldn’t be completed. (OSStatus error -10814.)”
    2017-08-17 13:22:45.694 FaceBook[1330:18946] Falling back to storing access token in NSUserDefaults because of simulator bug
    2017-08-17 13:22:45.696 FaceBook[1330:18946] -canOpenURL: failed for URL: “fbauth2:/” – error: “The operation couldn’t be completed. (OSStatus error -10814.)”

    Reply
  3. uday babariya says

    August 19, 2017 at 12:48 pm

    simple tutorial!!! great job brother!!!

    Reply
  4. Hafiz Babar says

    September 7, 2017 at 12:39 am

    Hi Bilal hope you are fine I followed your tutorial but blank webview appear after login button clicked. Please help me to solve this problem

    Reply
  5. Abhishek Singh says

    September 12, 2017 at 2:47 pm

    How to handle the situation:
    Steps:

    Tap ‘Facebook’
    Use Facebook app to validate
    Quit my app
    Finish Facebook app login and ‘open my app’
    Expected:
    Foundmi will log in

    Actual:
    The app does not log in

    Reply
  6. Jim says

    October 15, 2017 at 1:44 pm

    Good tutorial but it is not complete. You also need to:

    1. class ViewController: UIViewController, LoginButtonDelegate

    2. loginButton.delegate = self

    3.
    func loginButtonDidCompleteLogin(_ loginButton: LoginButton, result: LoginResult) {
    print(“logged in”)
    self.getFBUserData()
    }

    func loginButtonDidLogOut(_ loginButton: LoginButton) {
    print(“logged out”)
    }

    Reply
    • Awais Fayyaz says

      December 12, 2017 at 1:30 pm

      Wao.
      You caught errors really!

      Reply
  7. vijay kumar says

    November 10, 2017 at 9:03 am

    iam getting error like “No such module ‘FacebookLogin'”

    Reply
    • Belal Khan says

      November 12, 2017 at 8:51 am

      Have you added facebook sdk with cocoa pods?

      Reply
      • vijay says

        November 21, 2017 at 6:43 am

        how to add with cocoapods?

        Reply
  8. vijaykumar says

    November 12, 2017 at 3:17 pm

    problem solved .can you send me the source code for the login and regrastration form for the swift with backend php .for the post method?

    Reply
  9. vijay kumar says

    November 17, 2017 at 9:17 am

    how to add the facebook sdk using cocoapods?

    Reply
  10. chakravarthy says

    November 17, 2017 at 12:25 pm

    while i am running my code Type of expression is ambiguous without more context

    Reply
  11. munira says

    December 26, 2017 at 7:45 am

    why does it say “Type of expression is ambiguous without more context”?
    @objc func loginButtonClicked() {
    let loginManager = LoginManager()
    loginManager.logIn([ .publicProfile ], viewController: self) { loginResult in…
    there seems to be some problem with the ” [ .publicProfile ].
    can you please tell me why?

    Reply
    • Aaron J Miller says

      January 13, 2018 at 8:53 pm

      I got the same thing as Munira. This did not work for me

      Reply
    • Kenny says

      February 8, 2018 at 5:11 am

      This changed to ( readPermissions: [ .publicProfile ] in one of the SDK updates

      remember you can always construct a blank function to see how the parameters should be formatted

      if you type loginManager.login – xcode should pop up a choice including the stub for the function

      Reply
    • Yasin says

      March 4, 2018 at 6:17 pm

      I had the same problem., add readPermissions: right before [.publicProfile]

      Reply
    • marcelo says

      March 8, 2018 at 7:57 am

      loginManager.logIn(readPermissions: [.publicProfile], viewController: self)

      Reply
  12. Samir Rana says

    April 6, 2018 at 5:38 pm

    email not fetched this is the main issue

    Reply

Leave a Reply Cancel reply

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




About Me

belal khan simplified ios

Hello I am Belal Khan, founder and owner of Simplified iOS. I am currently pursuing MCA from St. Xavier's College, Ranchi. Apart from my academic I am a blogger, I run various websites and majority of them are about coding and development.

Connect with Me

Follow Simplified iOS

Simplified iOS

Popular Posts

  • Swift SQLite Tutorial for Beginners – Using… (99,380)
  • Swift PHP MySQL Tutorial – Connecting iOS App… (98,248)
  • UIWebView Example to Load URL in iOS using Swift in Xcode (79,974)
  • Download Full High Sierra Installer to Create Bootable USB (70,273)
  • Xcode Login Screen Example using Swift 3, PHP and MySQL (67,256)
  • How to Format USB on Mac? Formatting External Hard… (61,373)
  • Swift JSON Tutorial – Fetching and Parsing… (59,402)
  • Firebase Realtime Database Tutorial for Swift using Xcode (53,697)
  • iOS Registration Form Example using PHP and MySQL (48,915)
  • Xcode Text Field Tutorial for iOS Application using Swift (41,145)




About

Simplified iOS is a blog where you can find latest tutorials related to coding and app development for iphone and MAC OS. Here you can get Simplified iPhone, iPad and Mac OS development tutorial to know the things about Apple Development from basics to advanced level.

Quick Links

  • Advertise
  • Contact
  • Disclaimer
  • Privacy Policy
  • Write for Us

Copyright © 2017 · Simplified iOS· All rights Reserved. And Our Sitemap.All Logos & Trademark Belongs To Their Respective Owners·