With the rise of social media, Facebook login integration has become one of the must have features in mobile app. Despite the fact that every developer is integrating Facebook login into their apps, Facebook is doing a very poor job on updating their documentations. In fact, some of the documentations’ sample code are still written in Objective-C.
In this article, I will go through with you, step-by-step on how to:
- Setup Facebook App.
- Configure iOS project to use Facebook SDK.
- Integrate iOS app with Facebook SDK.
- Test Facebook login integration using test users.
Setup Facebook App
First, go to https://developers.facebook.com/apps/ and click on the “Add a New App” button. This will bring up a dialog that guide you through creating a new app ID.
Go ahead and enter your app name into the “Display Name” field and enter your email address into the “Contact Email” field. After that click “Create App ID” to proceed.
This should bring you to your app dashboard page.
At the left panel of the dashboard page, click on Settings → Basic, scroll to the bottom of the page and click on the “Add Platform” button, select iOS as your platform.
Once you selected iOS as your platform, you should see a web form that allows you to fill in your iOS app information.
Go ahead and copy the bundle identifier from your Xcode project’s application target and paste it into the “Bundle ID” field.
After that turn on “Single Sign On” and then click “Save Changes”.
With that, you have completed the setup required on your Facebook app.
Next up, let’s head over to terminal to perform the Facebook SDK installation process.
Configure iOS Project to Use Facebook SDK
Facebook SDK Installation
Note that we will be using CocoaPods to manage the Facebook SDK installation.
First step, fire up the terminal app and navigate to your iOS project root directory. Inside your project directory, run the following command to update your CocoaPods to the latest version.
$ sudo gem install cocoapods
After that, use the following command to initialize CocoaPods for your iOS project.
$ pod init
After running the above command, you should see a Podfile have been created in your project folder.
Open the Podfile with a text editor and add both FBSDKCoreKit
and FBSDKLoginKit
into the Podfile.
pod 'FBSDKCoreKit'
pod 'FBSDKLoginKit'
Lastly run the following command in your project root directory to install Facebook SDK.
$ pod install
After CocoaPods successfully installed the Facebook SDK, close your Xcode project and relaunch it using the project workspace file (.xcworkspace).
With that, you have successfully installed Facebook SDK into your Xcode project.
In future whenever there is a newer version of Facebook SDK being released, you can run the pod install
command at your root directory again to perform the update automatically.
Xcode Project Configuration
Now is the time to fire up your Xcode.
In your Xcode project navigator, look for info.plist, right click the info.plist file and select Open As → Source Code.
Insert the following XML snippet into the body of your info.plist
file just before the final </dict>
element.
<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-share-api</string> <string>fbauth2</string> <string>fbshareextension</string> </array>
After that, make sure you replace {your-app-id}
with your Facebook app ID and {your-app-name}
with your Facebook app display name. Note that for CFBundleURLSchemes
, you need to append your app ID behind the “fb” prefix.
Integrate iOS App with Facebook SDK
Update AppDelegate.swift
To enable Facebook SDK to post-process the results obtained after user login using native Facebook app or safari, you will have to connect your AppDelegate
class to the FBSDKApplicationDelegate
object.
To accomplish this, open up AppDelegate.swift and import FBSDKCoreKit
.
import FBSDKCoreKit
Next, add following code snippet to the application(_:didFinishLaunchingWithOptions:)
method.
ApplicationDelegate.shared.application(
application,
didFinishLaunchingWithOptions:
launchOptions
)
Finally add following method to AppDelegate.swift.
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
return ApplicationDelegate.shared.application(
app,
open: url,
options: options
)
}
Here’s how your AppDelegate.swift should looks like.
The last part of the integration is to add a Facebook-branded login button to your app. For the sake of simplicity, we will be using the login button included in the Facebook SDK — FBLoginButton
.
If you would like to use your own custom Facebook login button, checkout this article: Creating Custom Facebook Login Button in Swift.
With all that being said, let’s get back to adding FBLoginButton
to your app.
Adding FBLoginButton
First, import FBSDKLoginKit
to your view controller.
import FBSDKLoginKit
Next, copy the following code and paste it inside the viewDidLoad()
method of your view controller to show the FBLoginButton
at the center of the view.
// Add FBLoginButton at center of view controller
let loginButton = FBLoginButton()
loginButton.center = view.center
view.addSubview(loginButton)
Lastly, copy following code into viewDidLoad()
method to observe for changes in Facebook access token and print out the access token value. We can use this to verify that the user has successfully sign in with Facebook.
// Observe access token changes
// This will trigger after successfully login / logout
NotificationCenter.default.addObserver(forName: .AccessTokenDidChange, object: nil, queue: OperationQueue.main) { (notification) in
// Print out access token
print("FB Access Token: \(String(describing: AccessToken.current?.tokenString))")
}
Here’s how your viewDidLoad()
method should look like.
Test Facebook Login Integration Using Test Users
Since your have not make your Facebook app available in production, you can’t use a normal Facebook account to test out the login integration we have just implemented.
To test your app, you need to have a test user. Test user is a temporary Facebook account that you can use to test various features of your app.
To create a test user, head back to Facebook developer portal. At the left panel, select Roles → Test Users. Click the “Add” button at the top right corner to bring up the “Create Test Users” dialog.
Nothing much has to be done in the “Create Test Users” dialog, just click the “Create Test Users” button at the bottom to proceed.
At this stage you should see a test user has been created. Go ahead and click the “Edit” button on the right to set a password for this test user.
With that, we are now ready to test on the Facebook login integration.
Build and run your iOS app, you should see a blue color Facebook login button at the center of the screen. Click on the login button, you will be presented the Facebook login page. Enter the test user’s email address and password to proceed with login.
If you setup everything correctly, you should see a confirmation page. Click continue to dismiss the confirmation page. At this stage, you might notice that the login button’s title has been updated to “Log out”.
Pro Tip:
To clear the Facebook login history in your iOS simulator, open the Settings app, select Safari and then tap on “Clear History and Website Data”.
Lastly, activate Xcode debug console by pressing ⌘⇧C (command + shift + C). You should see that the Facebook access token has been printed out in the console area. You can use this access token to authenticate with Firebase or your own backend server.
Congratulations! You have successfully integrated Facebook login into your iOS app! 🕺🕺🕺
Here’s the sample project in Github.
Further Reading
This article should give you a very good idea on how to configure your app to integrate with the Facebook SDK.
If you have any questions or comments, feel free to let me know in the comment section below. I will try my best to answer all the questions.
You can follow me on Twitter for more article related to iOS development.
Thanks for reading and happy coding! 👨🏼💻
👋🏻 Hey!
While you’re still here, why not check out some of my favorite Mac tools on Setapp? They will definitely help improve your day-to-day productivity. Additionally, doing so will also help support my work.
- ✨ Bartender: Superpower your menu bar and take full control over your menu bar items.
- ✨ CleanShot X: The best screen capture app I’ve ever used.
- ✨ PixelSnap: Measure on-screen elements with ease and precision.
- ✨ iStat Menus: Track CPU, GPU, sensors, and more, all in one convenient tool.