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
- Visit the Getting Started with the Facebook iOS SDK documentation to download the Facebook SDK and install it.
- 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.
- 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.
- Create a new “Objective-C” Header file by clicking “File > New”
- 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 - 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”.
- Now your app should be able to access all of the APIs in the Facebook SDK.
- Add the following to your AppDelegate.swift. The “OpenURL” method allows your app to open again after the user has validated their login credentials.
- 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.
- 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.
- Add the following import statement to your Bridging-Header.h, right below the Core Kit entry.
#import
- Add the Facebook Login button to your ViewController.swift.
- 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.
- 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
- 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.
- First add the delegate FBSDKLoginButtonDelegate to the class definition.
class ViewController: UIViewController, FBSDKLoginButtonDelegate {
- 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") }
- 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
- 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:
- 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.
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).