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).
- After creating the Facebook App you will get your 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.
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 🙂
Mark Underwood says
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.
George Hanna says
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.)”
uday babariya says
simple tutorial!!! great job brother!!!
Hafiz Babar says
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
Abhishek Singh says
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
Jim says
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”)
}
Awais Fayyaz says
Wao.
You caught errors really!
vijay kumar says
iam getting error like “No such module ‘FacebookLogin'”
Belal Khan says
Have you added facebook sdk with cocoa pods?
vijay says
how to add with cocoapods?
vijaykumar says
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?
vijay kumar says
how to add the facebook sdk using cocoapods?
chakravarthy says
while i am running my code Type of expression is ambiguous without more context
munira says
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?
Aaron J Miller says
I got the same thing as Munira. This did not work for me
Kenny says
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
Yasin says
I had the same problem., add readPermissions: right before [.publicProfile]
marcelo says
loginManager.logIn(readPermissions: [.publicProfile], viewController: self)
Samir Rana says
email not fetched this is the main issue