(iOS) Facebook Login Button
Recently, I implemented Facebook login button using FBSDKLoginKit and Firebase. However, official documents from both websites were not so good enough. There would be some confusing points if you just followed the documents. In this article, I will introduce you the process of implementation step by step.
NOTE: The sample code for this article is available on my Github repository.
Step 1: Add your app on the ‘facebook for developers’ website
Go to https://developers.facebook.com/ and add your app from ‘My App’ button top right side of the page.
Step 2: Install dependencies 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 the ‘facebook for developers’ website (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.
Step 4: Configure your app on Facebook
Assuming you are still on your facebook app page, click 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.
Then you will see the configuration screen.
Basically, you can just follow the instructions.
4-1. Set up Your Development Environment
You can skip this part since you have already installed the pods.
4-2. Add your Bundle Identifier
You can find your Bundle ID on Xcode. Open your project on Xcode, then click on your project name on your project navigator -> select your project name on ‘TARGETS’ section -> general -> Bundle Identifier on Identity section.
4-3. Enable Single Sign on for Your App
Say “Yes” and save.
4-4. Configure Your info.plist
Add an XML snippet to ‘info.plist’ to configure the information, then add the flag ‘-ObjC’ to Other Linker Flags as the instruction says. The XML snippet looks something like this.
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb1111111111111111</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>YourAppIDComesHere</string>
<key>FacebookDisplayName</key>
<string>YourProjectNameComesHere</string>// Below is to use any of the Facebook dialogs
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-share-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
4-5. Connect App Delegate
At this point, you need to add the code to connect your app with Facebook SDK. Sadly, the code instruction is written in Objective-C. You can try Swiftify, a converter from objective-c to Swift, or just add the following code to your ‘AppDelegate.swift’ file.
Swiftify: https://objectivec2swift.com/#/converter/
import FBSDKCoreKitfunc application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
return true
}func application(_ app: UIApplication, open url: URL, options:[UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool { let handled: Bool = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[.sourceApplication] as? String, annotation: options[.annotation]) return handled
}
4-6: Add the Facebook Login Button
Inside of viewDidLoad()
in the ‘ViewController.swift’ file, add the following code to implement Facebook button programmatically.
import UIKIt
import FBSDKCoreKit
import FBSDKLoginKitclass ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad() let loginButton = FBSDKLoginButton()
// Optional: Place the button in the center of your view.
loginButton.center = view.center
view.addSubview(loginButton)
}
}
4-7: Add code to check login status
Your app should have only one person logged in at a time. Add the following code inside viewDidLoad()
to check the user’s login status.
if (FBSDKAccessToken.current() != nil) {
// User is logged in, do work such as go to next view controller.
}
‘FBSDKAccessToken currentAccessToken’ represents each person logged into your app. In the code above, the FBSDKLoginManager sets this token with ‘current()’ and adds the token into your cache key chain.
4–8: Ask for Permissions
When you login with the services such as Google, Facebook, or Twitter, it is usual to be asked for permissions. In order to request additional read permissions, you can add the code to viewDidLoad()
as below.
loginButton.readPermissions = ["public_profile", "email"]
4–9: 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.
Step 5: Add firebase to your app
On the Firebase Console, click on the setting icon at the right of Project Overview and go to Project Settings. You should see ‘Your apps’ section. Select iOS and move on to the app creation process. Basically, you just need to follow the instruction,
5-1: Register app
Add your app’s Bundle Identifier.
5–2: Download GoogleService-info.plist
You will download ‘GoogleService-info.plist’ file at here and add it to your Xcode project.
5–3: Add Firebase SDK
You will be told to add the pod to install Firebase SDK into your project. The instruction tells you to add only pod ‘Firebase/Core’
, however, you will need pod ‘Firebase/Auth’
to actually authenticate the user in Firebase. Therefore, just add the following code in your Podfile instead of just adding pod ‘Firebase/Core’
. Don’t forget to run pod install
.
pod 'Firebase/Core'
pod 'Firebase/Auth'
5–4: Add Installation Code
Add the following code in your AppDelegate. Don’t forget to add import Firebase
at the top.
FirebaseApp.configure()
5–5: Run your app to verify installation
You can just skip this since there is still work to do.
Step 6: Authenticate with Firebase
Finally, add some lines in your ViewController.swift file. You can check out the official Firebase document here, however, it is not clear. loginButton()
and loginButtonDidLogOut()
are the functions that are needed to conform to FBSDKLoginButtonDelegate
.
Note:
If you get an error saying “Falling back to loading access token from NSUserDefaults because of simulator bug”, you need to use the real device. This error seems like the bug related to Facebook SDK.
import UIKIt
import Firebase
import FBSDKCoreKit
import FBSDKLoginKitclass ViewController: UIViewController, FBSDKLoginButtonDelegate {
override func viewDidLoad() {
super.viewDidLoad() let loginButton = FBSDKLoginButton()
loginButton.delegate = self
// Optional: Place the button in the center of your view.
loginButton.center = view.center
view.addSubview(loginButton)
} func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
if let error = error {
print(error.localizedDescription)
return
} let credential = FacebookAuthProvider.credential(withAccessToken: FBSDKAccessToken.current().tokenString) Auth.auth().signInAndRetrieveData(with: credential) { (authResult, error) in
if let error = error {
// ...
return
}
// User is signed in
// ...
}
// ...
} func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
// Do something when the user logout
print("Logged out")
}
}
When you are done with all the steps, your app is good to go. Build and run the app. Try to login with the button you have just implemented. If you can go through the Facebook authentication process without any error and find your information on your Firebase Authentication menu, it means you have working Facebook Login Button now.
Optional: Custom Facebook login button
In case you want to implement the button with your own design, there is a way.
Step 1: Create a UIButton object on a storyboard
Add an UIButton from the UI library.
Step 2: Add an IBAction
In your ViewController, create an IBAction like the code below and connect it with the button you’ve just added on the storyboard.
@IBAction func facebookLogin(sender: AnyObject) {
let LoginManager = FBSDKLoginManager() LoginManager.logIn(withReadPermissions: ["public_profile", "email"], from: self) { (result, error) in if let error = error {
print("Failed to login: \(error.localizedDescription)")
return
} guard let accessToken = FBSDKAccessToken.current() else {
print("Failed to get access token")
return
} let credential = FacebookAuthProvider.credential(withAccessToken: accessToken.tokenString) // Perform login by calling Firebase APIs
Auth.auth().signInAndRetrieveData(with: credential) { (user, error) in
if let error = error {
print("Login error: \(error.localizedDescription)")
let alertController = UIAlertController(title: "Login Error", message: error.localizedDescription, preferredStyle: .alert)
let okayAction = UIAlertAction(title: "OK", style: .cancel, handler: nil)
alertController.addAction(okayAction)
self.present(alertController, animated: true, completion: nil)
return
}
// self.performSegue(withIdentifier: self.signInSegue, sender: nil)
}
}
}
That’s everything you need to implement your own Facebook Login button and connect it to Firebase. If you have any good ways to implement, please let me know. Any feedback would be appreciated.
Thank you for reading this!
Reference:
Using Firebase to Integrate Facebook Login in iOS:
Appshttps://www.appcoda.com/firebase-facebook-login/
Firebase facebook login official document:
https://firebase.google.com/docs/auth/ios/facebook-login
Facebook Login for iOS — Quickstart
https://developers.facebook.com/docs/facebook-login/ios
Facebook Login for iOS — Advanced
https://developers.facebook.com/docs/facebook-login/ios/advanced
Facebook Login (Written in Japanese)
http://grandbig.github.io/blog/2016/05/14/facebook-login-for-swift/