Hello guys!
Today I’m going to show you how to integrate Facebook login to your iOS app using Swift.
Login to your Facebook and go to developers.facebook.com.
Click “My Apps” and click “Add a New App”
Name the app and select the suitable category then click Create App ID.
YOU SHALL NOT PASS!!!. 😀
You’ll be redirected to this page. Click Choose a Platform.
You’ll then reach here. Click iOS.
Download the SDK from here.
Open your project’s info.plist as Source Code.
Paste all the .plist code from this page to your .plist.
Your final info.plist will look something like this
Finally at the end of the page, paste your Bundle identifier, then click next.
Open your project and Unzip FacebookSDK folder and drag FBSDKCoreKit.framwork and FBSDKLoginKit.framework into your project.
Since our environment is all setup. Now It’s time to role sleeves and start code.
Open your AppDelegate, import FBSDKCoreKit and FBSDKLoginKit and paste the following code.
1 2 3 4 5 6 |
//This goes in your DidFinishLaunchingWithOptions 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) } |
Your AppDelegate should look like this
.
Now add two View Controllers and embed a Navigation Controller to it.
Drag a button to the first View Controller and name it as LOGIN and create an action event for it. Drag a segue from root view controller to its embedded view controller and name it as “login”.
In our viewDidLoad we need to enable the listener that will provide us all the credentials of the logged in user.
1 2 |
FBSDKProfile.enableUpdatesOnAccessTokenChange(true) NSNotificationCenter.defaultCenter().addObserver(self, selector: "profileUpdated:", name: FBSDKProfileDidChangeNotification, object: nil) |
and the selector event for this.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
func profileUpdated(notification: NSNotification) { if FBSDKAccessToken.currentAccessToken() != nil{ let name = FBSDKProfile.currentProfile().name let uid = FBSDKProfile.currentProfile().userID let fname = FBSDKProfile.currentProfile().firstName let lname = FBSDKProfile.currentProfile().lastName let pplink = FBSDKProfile.currentProfile().imageURLForPictureMode(FBSDKProfilePictureMode.Square, size: CGSize(width: 400,height: 400)) print("name:(name)") print("User ID:(uid)") print("first(fname)") print("last:(lname)") print("image:(String(pplink))") self.getUserEmail() } else { print("logged out") } } |
You’ll get full name, first name, last name, and profile picture. In order to get the email. We need to do a graph request.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
func getUserEmail() { let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters:["fields": "email"], HTTPMethod: "GET") graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in if ((error) != nil) { // Process error print("Error: (error)") } else { let userEmail : NSString = result.valueForKey("email") as! NSString let email = userEmail as String print("Email:(email)") } }) } |
Now, In your login button event.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
@IBAction func loginButton(sender: AnyObject) { let login: FBSDKLoginManager = FBSDKLoginManager() login.logInWithReadPermissions(["public_profile","email","user_friends"], fromViewController: self) { (result: FBSDKLoginManagerLoginResult!, error) -> Void in if ((error) != nil) { // Process error } else if result.isCancelled { // Handle cancellations } else { self.performSegueWithIdentifier("login", sender: nil) } } } |
Create an action of argument type UIStoryboardSegue in your root view controller so that you can perform an unwind segue when you logout.
1 2 3 |
@IBAction func returnOnLogout(storyboard: UIStoryboardSegue){ } |
Add a new class for the second view controller, add a button to it and rename it as Logout and create an action for it.
1 2 3 4 5 6 7 8 |
@IBAction func logout(sender: AnyObject) { if FBSDKAccessToken.currentAccessToken() != nil { let logout = FBSDKLoginManager() logout.logOut() } } |
Hold ctrl on your button and drag it all the way to Exit responder and also hide the navigation bar.
1 |
self.navigationItem.hidesBackButton = true |
Save and run the app. You’ll get the following results.
I hope that it would have helped.
Here is the source code for this on Github.
Sayonara!
3 Comments