Brian Coleman

  • Home
  • ABOUT
  • SERVICES
  • PORTFOLIO
  • BLOG
  • Contact

Tutorial: How To Use Login in Facebook SDK 4.1.x for Swift

It’s been a long time but Facebook has finally released a new version of their SDK. It’s not built using Swift, I guess that still makes it compatible with Objective-C. In this tutorial we’ll go through the steps to install the SDK and implement Facebook Login using the SDK in Swift.

Get your Application Setup with the Facebook SDK

  1. Visit the Getting Started with the Facebook iOS SDK documentation to download the Facebook SDK and install it.
  2. Add the FacebookSDKCoreKit.Framework to your project as you normally would. Drag it or add it using the “Linked Frameworks and Libraries” within your target settings.
  3. You won’t be able to use the normal #import <FBSDKCoreKit/FBSDKCoreKit.h> to link the framework so you need to do a work around by creating a Bridging Header.
  4. Create a new “Objective-C” Header file by clicking “File > New”
    Screen Shot 2015-03-27 at 9.17.15 AM
    Screen Shot 2015-03-27 at 9.18.41 AM

  5. All you need in the Bridging-Header.h is the import statement for the Facebook SDK.
    //
    //  Bridging-Header.h
    //  FacebookTutorial
    //
    //  Created by Brian Coleman on 2015-03-27.
    //  Copyright (c) 2015 Brian Coleman. All rights reserved.
    //
    
    #ifndef FacebookTutorial_Bridging_Header_h
    #define FacebookTutorial_Bridging_Header_h
    
    #import 
    
    #endif
    
  6. Add it to your target’s build settings:In Xcode, if you go into the build settings for your target, and scroll all the way down you’ll find a “Swift Compiler – Code Generation” section.

    Set “Objective-C Bridging Header” to <#PROJECT_NAME>/Bridging-Header.h

    “Install Objective-C Compatibility Header”, should be set to “Yes”.

    Here’s what it looks like:
    Screen Shot 2015-03-27 at 9.24.17 AM

  7. Now your app should be able to access all of the APIs in the Facebook SDK.
  8. Add the following to your AppDelegate.swift. The “OpenURL” method allows your app to open again after the user has validated their login credentials.
  9. The FBSDKAppEvents.activateApp() method allows Facebook to capture events within your application including Ads clicked on from Facebook to track downloads from Facebook and events like how many times your app was opened.
    //
    //  AppDelegate.swift
    //  FacebookTutorial
    //
    //  Created by Brian Coleman on 2015-03-27.
    //  Copyright (c) 2015 Brian Coleman. All rights reserved.
    //
    
    import UIKit
    
    @UIApplicationMain
    class AppDelegate: UIResponder, UIApplicationDelegate {
    
        var window: UIWindow?
    
        func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
            // Override point for customization after application launch.
            return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
        }
        
        func application(application: UIApplication,
            openURL url: NSURL,
            sourceApplication: String?,
            annotation: AnyObject?) -> Bool {
                return FBSDKApplicationDelegate.sharedInstance().application(
                    application,
                    openURL: url,
                    sourceApplication: sourceApplication,
                    annotation: annotation)
        }
    
        func applicationWillResignActive(application: UIApplication) {
            // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
            // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
        }
    
        func applicationDidEnterBackground(application: UIApplication) {
            // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
            // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
        }
    
        func applicationWillEnterForeground(application: UIApplication) {
            // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
        }
    
        func applicationDidBecomeActive(application: UIApplication) {
            // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
            FBSDKAppEvents.activateApp()
        }
    
        func applicationWillTerminate(application: UIApplication) {
            // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
        }
    
    }
    

Facebook Login for iOS

Now we’ll setup our app to use Facebook Login.

  1. Add the FacebookSDKLoginKit.Framework & Bolts.framework to your project just like your did with the FacebookSDKCoreKit.Framework. Drag it or add it using the “Linked Frameworks and Libraries” within your target settings.
  2. Add the following import statement to your Bridging-Header.h, right below the Core Kit entry.
    #import 
    
  3. Add the Facebook Login button to your ViewController.swift.
  4. After you add the button, you should update your view controller to check for an existing token at load. This eliminates an unnecessary app switch to Facebook if someone already granted permissions to your app.
  5. When you add Facebook Login, your app can ask someone for permissions on a subset of that person’s data. Use the readPermissions or publishPermissions property of the FBSDKLoginButton.
    //
    //  ViewController.swift
    //  FacebookTutorial
    //
    //  Created by Brian Coleman on 2015-03-27.
    //  Copyright (c) 2015 Brian Coleman. All rights reserved.
    //
    
    import UIKit
    
    class ViewController: UIViewController {
    
        override func viewDidLoad() {
            super.viewDidLoad()
            // Do any additional setup after loading the view, typically from a nib.
            
            if (FBSDKAccessToken.currentAccessToken() != nil)
            {
                // User is already logged in, do work such as go to next view controller.
            }
            else
            {
                let loginView : FBSDKLoginButton = FBSDKLoginButton()
                self.view.addSubview(loginView)
                loginView.center = self.view.center
                loginView.readPermissions = ["public_profile", "email", "user_friends"]
                loginView.delegate = self
            }
            
        }
    
        override func didReceiveMemoryWarning() {
            super.didReceiveMemoryWarning()
            // Dispose of any resources that can be recreated.
        }
    
    }
    

Using the FBSDKLoginButtonDelegate Methods

  1. Add in the additional code for the FBSDKLoginButtonDelegate. This is helpful to know if the user did login correctly and if they did you can grab their information.
  2. First add the delegate FBSDKLoginButtonDelegate to the class definition.
    class ViewController: UIViewController, FBSDKLoginButtonDelegate {
    
  3. Add the following callback methods to your View Controller.
        // Facebook Delegate Methods
        
        func loginButton(loginButton: FBSDKLoginButton!, didCompleteWithResult result: FBSDKLoginManagerLoginResult!, error: NSError!) {
            println("User Logged In")
            
            if ((error) != nil)
            {
                // Process error
            }
            else if result.isCancelled {
                // Handle cancellations
            }
            else {
                // If you ask for multiple permissions at once, you
                // should check if specific permissions missing
                if result.grantedPermissions.contains("email")
                {
                     // Do work
                }
            }   
        }
        
        func loginButtonDidLogOut(loginButton: FBSDKLoginButton!) {
            println("User Logged Out")
        }
    
  4. Here is an extra method to grab the Users Facebook data. You can call this method anytime after a user has logged in by calling self.returnUserData().
        func returnUserData()
        {
            let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
            graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
               
                if ((error) != nil)
                {
                    // Process error
                    println("Error: \(error)")
                }
                else
                {
                    println("fetched user: \(result)")
                    let userName : NSString = result.valueForKey("name") as! NSString
                    println("User Name is: \(userName)")
                    let userEmail : NSString = result.valueForKey("email") as! NSString
                    println("User Email is: \(userEmail)")
                }
            })
        }
    

Enter your Facebook App Information

  1. There is one final step needed to be performed, and that is to add three new keys to the project’s .plist file. So, open it by clicking on the Supporting Files group in the Project Navigator and then on the Info.plist file. Add a new key named FacebookAppID, and as its value paste the App ID value which you can copy from the Facebook dashboard, at the top of it. Similarly, add the FacebookDisplayName key, and in its value paste the Display Name.Finally, create a new key named URL Types, and set its type to array with one item only. Give it the URL Schemes title and make it an array too. In the one and only item that should be contained, set the app ID value you copied from the Facebook dashboard, prefixing it with the fb literal. The image below shows all the three additions on the .plist file:
    Screen Shot 2015-03-27 at 10.12.39 AM
  2. Compile your project and you should see the following screen. Once you click the “Log in with Facebook” button, it should kick you out to the Facebook App or the Facebook website for the user to login. After they have, it’ll kick back to your app and you’ll see the user information in the console.
    Screen Shot 2015-03-27 at 11.43.09 AM
    Now it’s up to you to use the users information as you wish. Maybe to populate a user profile or to pull the users Facebook friends so you can build a leaderboard.


You can grab the full source code for this tutorial. Note: Created using XCode 6.3 (Swift 1.2).
If you need it built using Xcode 6.2 (Swift 1.1).

Tutorial: Check for Internet Connection in SwiftTutorial: How To Share in Facebook SDK 4.1.x for Swift
Brian Coleman

Manager, Mobile Development at Rogers Communications with over 15 years of multifaceted experience including development, design, business analysis and project management working directly with clients in a consulting capacity throughout the full software life cycle.

March 27, 2015 Frameworks, Swift, Tutorialsfacebook, ios8, swift, tutorial
Follow Me
    
Categories
  • About Me
  • Frameworks
  • My Apps
  • News
  • Strategy
  • Swift
  • Tools
  • Tutorials
  • tvOS
  • Uncategorized
  • Videos
  • Watch
Archives
  • May 2016
  • January 2016
  • October 2015
  • July 2015
  • May 2015
  • April 2015
  • March 2015
  • November 2014
  • October 2014
  • September 2014
  • July 2014
  • June 2014
  • September 2013
  • August 2013
  • July 2013
  • June 2013
  • May 2013
  • April 2013
  • March 2013
  • February 2013
Recent Posts
  • Classix for iPhone, iPad & Apple TV
  • Tutorial: How to test your app for IPv6 compatibility
  • Tutorial: Testing SSL using Charles Proxy on an iOS Device
  • Tutorial: 3D Touch – Quick Actions in Swift
  • tvOS Tutorial: Top Shelf in Swift
Featured Apps
Classix
Sportsnet
TAGS
tutorialswiftios8iosobjective-cvideogamesstrategynewsframeworkappsmonitizefacebookwatchappleios7toolstvosios9apiprovisionsocialtutorialsbooksdesignbookiapIPv6iTunes Connect
Search
TAGS
tutorialswiftios8iosobjective-cvideogamesstrategynewsframeworkappsmonitizefacebookwatchappleios7toolstvosios9apiprovisionsocialtutorialsbooksdesignbookiapIPv6iTunes Connect
ABOUT
Brian is a Lead iOS/tvOS Developer from Toronto with over 18 years of multifaceted experience including development, design, business analysis and project management.

FOLLOW ME
    
Email Subscription
Sign up for my newsletter to receive the latest news and tutorials posted.

Enter your email address:

2023 © Brian Coleman