Get updates on your email

Thursday, August 3, 2017

Login with Facebook using Swift

The most simple example of login with facebook suign swift 3.

Open facebook developers portal

Add a new app

Give you app a display name

Select settings from left and you'll see this. You need to select Add Platform from this.

Select iOS

Create a new xCode project and copy the bundle ID

Paste the bundle ID in facebook developer iOS platform and turn the Single Sign On as shown in the screenshot below

Save the changes. That is it for the facebook developers portal. Lets get back to xCode.

Open info.plist as source code and paste this code over there. YOU NEED TO REPLACE THE APP ID AND DISPLAY NAME AS YOURS

<string>Sample Test App</string>
Careful while copying the code above you need to replace the CFBundleURLSchemes and FacebookAppID and FacebookDisplayName

Now let's add Facebook SDK with Pods. Create a pod file in your project and add these three in them:

pod 'FBSDKCoreKit'
pod 'FBSDKShareKit'
pod 'FBSDKLoginKit'

It'll look like this

Open terminal.

cd <path to the project>

pod install

After successful installation you need to open .xcworkspace

So let's setup the UI first. Add three UILabel and two UIView in your storyboard view controller.

Next change the custom class of the square view to FBSDKProfilePictureView and the rectangle view below to FBSDKLoginButton

Open AppDelegate.swift and add the following
import FBSDKCoreKit
in didFinishLaunchingWithOptions add

FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
next add this method in app delegate

func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
        let handle = FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])
        return handle

Next attach all the elements in the viewController.swift class. Open view controller and add

import FBSDKLoginKit

and attach the following with their respective outlet
    @IBOutlet var accountStatusLabel: UILabel!
    @IBOutlet var loginButton: FBSDKLoginButton!
    @IBOutlet var userEmail: UILabel!
    @IBOutlet var userName: UILabel!
    @IBOutlet var profilePicture: FBSDKProfilePictureView!

Next to UIViewController in viewController.swift add FBSDKLoginButtonDelegate

In ViewDidLoad add

loginButton.delegate = self
        loginButton.readPermissions = ["email", "public_profile"]
        accountStatusLabel.text = "Welcome! Kindly login to continue"
        userName.isHidden = true
        userEmail.isHidden = true

Next we add the delegate methods of FBSDKLoginButton. Add the following two functions in viewController.swift

func loginButtonDidLogOut(_ loginButton: FBSDKLoginButton!) {
        userName.isHidden = true
        userEmail.isHidden = true
        accountStatusLabel.text = "You are logged out"

    func loginButton(_ loginButton: FBSDKLoginButton!, didCompleteWith result: FBSDKLoginManagerLoginResult!, error: Error!) {
        if error != nil {

and finally add updateUserProfile which is a custom function

func updateUserProfile()
        FBSDKGraphRequest(graphPath: "/me", parameters: ["fields": "id, name, email"]).start { (connection, result, err) in
            if err != nil {
                print("Request failed: ", err!)
            if let dictionary = result as? [String: AnyObject] {
                self.userName.isHidden = false
                self.userEmail.isHidden = false
                self.accountStatusLabel.text = "Welcome"
                self.profilePicture.profileID = dictionary["id"] as! String
                self.userName.text = dictionary["name"] as? String
                self.userEmail.text = dictionary["email"] as? String

Save and run the program. Here are the results:

No comments:

Post a Comment