iOS

Add Facebook login to your iOS App using Swift tutorial

Introduction

This section explains how you can create an app with user registration using Facebook Login and Parse Server core features through Back4App.

Prerequisites

To complete this tutorial, you need:

Step 1 - Facebook Set up

To start using Facebook functions, you need to:

  1. Go to the Facebook Developer Website and create an account and an app.
  2. Add your application’s Facebook Application ID on your Parse application’s settings page.
  3. Follow Facebook’s instructions for getting started with the Facebook SDK to create an app linked to the Facebook SDK.
  1. Go to your App dashboard at Back4App Website and click on Server Settings.
  2. Find the “Facebook Login” block and click on Settings. The “Facebook Login” block looks like this:
  3. Go back to your XCode Project, open your info.plist copy the code from Facebook Configuration, Step 4a, item 2, and paste it in the <dict>...</dict> part of your info.plist.
  4. In order to use a dialog box from Facebook, also copy and paste the code from section 4a, item 3 into your info.plist file.
  5. Save

Step 3 - Setting up your App

  1. Add the following to your application:didFinishLaunchingWithOptions: method, after you’ve initialized the Parse SDK:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    
     import FBSDKCoreKit
     import Parse
    
     // AppDelegate.swift
     func application(application: UIApplicatiofunc application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
     // Initialize Parse.
     let parseConfig = ParseClientConfiguration {
         $0.applicationId = "parseAppId"
         $0.clientKey = "parseClientKey"
         $0.server = "parseServerUrlString"
     }
     Parse.initialize(with: parseConfig)
     PFFacebookUtils.initializeFacebook(applicationLaunchOptions: launchOptions)
     }
    
  2. Add the following handlers in your app delegate:
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    
     func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
    
     return FBSDKApplicationDelegate.sharedInstance().application(
                 application,
                 open: url,
                 sourceApplication: sourceApplication,
                 annotation: annotation
         )
    
     }
    
     func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey: Any] = [:]) -> Bool {
    
     return FBSDKApplicationDelegate.sharedInstance().application(
                 app,
                 open: url,
                 sourceApplication: options[.sourceApplication] as? String,
                 annotation: options[.annotation]
         )
    
     }
    
     //Make sure it isn't already declared in the app delegate (possible redefinition of func error)
     func applicationDidBecomeActive(_ application: UIApplication) {
     FBSDKAppEvents.activateApp()
     }
    

Step 4 - Log in & Sign Up

PFUser provides a way to allow your users to log in or sign up through Facebook. This is done by using the logInInBackgroundWithReadPermissions method like so:

1
2
3
4
5
6
7
8
9
10
11
12
    PFFacebookUtils.logInInBackground(withReadPermissions: permissions) {
    (user: PFUser?, error: Error?) in
    if let user = user {
        if user.isNew {
        print("User signed up and logged in through Facebook!")
        } else {
        print("User logged in through Facebook!")
        }
    } else {
        print("Uh oh. The user cancelled the Facebook login.")
    }
    }

When this code is run, the following happens:

  1. The user is shown the Facebook login dialog.
  2. The user authenticates via Facebook, and your app receives a callback using handleOpenURL.
  3. Our SDK receives the user’s Facebook access data and saves it to a PFUser. If no PFUser exists with the same Facebook ID, then a new PFUser is created.
  4. Your code block is called with the user.
  5. The current user reference will be updated to this user.

The permissions argument is an array of strings that specifies what permissions your app requires from the Facebook user. These permissions must only include read permissions.

To acquire publishing permissions for a user so that your app can, for example, post status updates on their behalf, you must call [PFFacebookUtils logInInBackgroundWithPublishPermissions:]:

1
2
3
4
5
6
PFFacebookUtils.logInInBackgroundWithPublishPermissions(["publish_actions"], {
  (user: PFUser?, error: NSError?) -> Void in
  if user != nil {
    // Your app now has publishing permissions for the user
  }
})

Step 5 - Linking

If you want to associate an existing PFUser to a Facebook account, you can link it like so:

1
2
3
4
5
6
7
8
if !PFFacebookUtils.isLinkedWithUser(user) {
  PFFacebookUtils.linkUserInBackground(user, withReadPermissions: nil, {
    (succeeded: Bool?, error: NSError?) -> Void in
    if succeeded {
      print("Woohoo, the user is linked with Facebook!")
    }
  })
}

Step 6 - UnLinking

If you want to unlink Facebook from a user, simply do this:

1
2
3
4
5
6
PFFacebookUtils.unlinkUserInBackground(user, {
  (succeeded: Bool?, error: NSError?) -> Void in
  if succeeded {
    print("The user is no longer associated with their Facebook account.")
  }
})