Skip to content

FacebookAuth

tuanta-0175 edited this page Mar 2, 2023 · 22 revisions

A simple and efficient Swift library for Facebook Login in iOS. The class makes use of the FirebaseAuth and Facebook Login SDK for iOS to provide a user-friendly and customizable sign-in experience, while handling the authentication process in the background.

Features

Installation

Requirement

  • iOS 13 and above
  • Swift 5.7 and above

Swift Package Manager

To install FacebookAuth using Swift Package Manager, add the following to your Package.swift file:

dependencies: [
    .package(url: "https://github.com/sun-asterisk/tech-standard-ios-auth", from: "1.0.0")
]

Select FacebookAuth package, or FacebookAuthRx package if you use RxSwift.

Usage

Prerequisites

In order to use FacebookAuth, you will need to have a Facebook App and Developer Account. You can create one at developers.facebook.com.

You will also need to add the Facebook Login SDK to your iOS project and configure Firebase.

Example

Here's an example of how you can use FacebookAuth to log in a user and retrieve their basic profile information:

import FacebookAuth

let facebookAuth = FacebookAuth.shared

// Log in the user
facebookAuth.login(permissions: [.publicProfile], fields: "id, name, email", viewController: self) { result in
    switch result {
    case .success(let authDataResult, let userInfo):
        print("Successfully logged in as \(userInfo["name"])")
    case .failure(let error):
        print("Failed to log in: \(error)")
    }
}

// Get the user's profile information
facebookAuth.getUserInfo(fields: "id, name, email") { result in
    switch result {
    case .success(let userInfo):
        print("User info: \(userInfo)")
    case .failure(let error):
        print("Failed to retrieve user info: \(error)")
    }
}

You can also use the logout() method to log out the current user:

if let error = facebookAuth.logout() {
    print("Failed to log out: \(error)")
} else {
    print("Successfully logged out")
}

Documentation

Class diagram

    classDiagram
    BaseAuth <|-- FacebookAuth
    
    class BaseAuth {
    +SignInState state
    +SignInMethod method
    +setSignInState()
    +resetSignInState()
    +cleanUp()
    }

    class FacebookAuth {
    +Bool isLoggedIn
    +AuthCredential? credential
    +login(permissions, fields, viewController, completion)
    +logout()
    +getAccessToken()
    +getUserInfo(fields, completion)
    +setDelegate(for button, fields, loginCompletion, logoutCompletion)
    +removeDelegate(for button)
    }
Loading

Login Facebook and Firebase Authentication

Sequence diagram

sequenceDiagram
  participant iOSApp
  participant Facebook
  participant Firebase
  iOSApp->>+Facebook: Request: login(permissions)
  break login fails
  Facebook-->>iOSApp: Error(code)
  iOSApp->>iOSApp: throws error
  end
  Facebook-->>-iOSApp: OK(token)
  iOSApp->>iOSApp: creates credential using Facebook token
  iOSApp->>+Firebase: Request: login(credential)
  break login fails
  Firebase-->>iOSApp: Error(code)
  iOSApp->>iOSApp: logs out Facebook <br/> throws error
  end
  Firebase-->>-iOSApp: OK(login result)
  iOSApp->>+Facebook: Request: user info
  break getting user info fails
  Facebook-->>iOSApp: Error(code)
  iOSApp->>iOSApp: logs out Facebook <br/> logs out Firebase <br/> throws error
  end
  Facebook-->>-iOSApp: OK(user info)
  iOSApp->>iOSApp: updates sign-in state <br/> returns login result and user info
Loading

Declaration

func login(
    permissions: [Permission],
    fields: String,
    viewController: UIViewController?,
    completion: ((Result<(AuthDataResult, [String : Any]?), Error>) -> Void)? = nil
)

Parameters

  • permissions: An array of Permission objects that specify the permissions the app is requesting from the user’s Facebook account.

  • fields: A comma-separated string of fields to be returned in the response from Facebook’s Graph API. (Reference)

  • viewController: An optional UIViewController object that is used to present the Facebook login screen.

  • completion: An optional closure that is called when the login process is completed. The completion handler takes a Result object, which contains either an AuthDataResult object and a dictionary of the fields returned for the user, or an error if the login failed.

Discussion

This function uses the Facebook SDK to initiate the login flow and presents the login dialog to the user. After the user grants the permissions, the function logs in to Firebase Authentication and retrieves the user’s auth data and additional fields and returns them in the completion handler. The completion handler is optional and will only be called if provided. The function should be called when the user wants to log in to the app using their Facebook account.

Overload methods

// Async/await
func login(permissions: [Permission],
           fields: String,
           viewController: UIViewController?) async -> Result<(AuthDataResult, [String: Any]?), Error>

// Combine
func login(permissions: [Permission],
           fields: String,
           viewController: UIViewController?) -> AnyPublisher<(AuthDataResult, [String: Any]?), Error>

// RxSwift
func login(permissions: [Permission],
           fields: String,
           viewController: UIViewController?) -> Observable<(AuthDataResult, [String: Any]?)>

Login Facebook

Sequence diagram

sequenceDiagram
  participant iOSApp
  participant Facebook
  iOSApp->>+Facebook: Request: login(permissions)
  break login fails
  Facebook-->>iOSApp: Error(code)
  iOSApp->>iOSApp: throws error
  end
  Facebook-->>-iOSApp: OK
  iOSApp->>+Facebook: Request: get-user-info
  break getting user info fails
  Facebook-->>iOSApp: Error(code)
  iOSApp->>iOSApp: logs out Facebook <br/> throws error
  end
  Facebook-->>-iOSApp: OK(user info)
  iOSApp->>iOSApp: updates sign-in state <br/> returns user info
Loading

Declaration

func login(
    permissions: [Permission],
    fields: String,
    viewController: UIViewController?,
    completion: ((Result<[String : Any]?, Error>) -> Void)? = nil
)

Parameters

  • permissions: An array of Permission objects that specify the permissions the app is requesting from the user’s Facebook account.

  • fields: A comma-separated string of fields to be returned in the response from Facebook’s Graph API. (Reference)

  • viewController: An optional UIViewController object that is used to present the Facebook login screen.

  • completion: An optional closure that is called when the login process is completed. The closure takes a single argument of type Result<[String: Any]?, Error>, where the .success case includes a dictionary of the fields returned for the user, and the .failure case contains an error object describing the failure.

Discussion

This function uses the Facebook SDK to initiate the login flow and presents the login dialog to the user. After the user grants the permissions, the function retrieves the user’s fields and returns them in the completion handler. The completion handler is optional and will only be called if provided. The function should be called when the user wants to log in to the app using their Facebook account.

Overload methods

// Async/await
func login(permissions: [Permission],
           fields: String,
           viewController: UIViewController?) async -> Result<[String: Any]?, Error>

// Combine
func login(permissions: [Permission],
           fields: String,
           viewController: UIViewController?) -> AnyPublisher<[String: Any]?, Error>

// RxSwift
func login(permissions: [Permission],
           fields: String,
           viewController: UIViewController?) -> Observable<[String: Any]?>

Logout Facebook and Firebase Authentication

Sequence diagram

sequenceDiagram
  participant iOSApp
  alt using Firebase
  iOSApp->>iOSApp: signs out Firebase
  break sign-out fails
  iOSApp->>iOSApp: returns error
  end
  iOSApp->>iOSApp: logs out Facebook <br/> returns nil
  else 
  iOSApp->>iOSApp: logs out Facebook <br/> returns nil
  end
Loading

Declaration

func logout() -> Error?

Return Value

An optional Error object, which will be nil if the logout is successful, or contain an error message if there was a problem logging out.

Discussion

This function uses the Facebook SDK to log out the user from their Facebook account and clear the session data. It should be called when the user wants to log out from the app. This function will also clear the Firebase Authentication user if it was logged in using Facebook.


Get the Facebook Access Token of the currently logged-in user

Sequence diagram

sequenceDiagram
  participant iOSApp
  alt token exists
  iOSApp->>iOSApp: returns Facebook token
  else token not exists
  iOSApp->>iOSApp: returns nil
  end
Loading

Declaration

func getAccessToken() -> AccessToken?

Return Value

An AccessToken object, which holds the user’s access token. If the user is not logged in or the token is not available, it returns nil.

Discussion

This function is used to retrieve the user’s access token. The function should be called when the user is logged in successfully.


Fetches the user's information from Facebook

Sequence diagram

sequenceDiagram
  participant iOSApp
  participant Facebook
  iOSApp->>+Facebook: Request: get-user-info
  Facebook-->>-iOSApp: OK(user info)
  iOSApp->>iOSApp: returns user info
Loading

Declaration

func getUserInfo(
    fields: String,
    completion: @escaping (Result<[String : Any]?, Error>) -> Void
)

Parameters

  • fields: A comma-separated string of fields to be returned in the response from Facebook’s Graph API. (Reference)

  • completion: A completion handler that gets called after the user’s information has been retrieved.

Discussion

This function uses the Facebook SDK to make a request to the Facebook Graph API to fetch the user’s information based on the fields provided and returns the data in the completion handler. The completion handler is mandatory and should be provided to handle the response, the function should be called when the user is logged in successfully.

Overload methods

// Async/await
func getUserInfo(fields: String) async -> Result<[String: Any]?, Error>

// Combine
func getUserInfo(fields: String) -> AnyPublisher<[String: Any]?, Error>

// RxSwift
func getUserInfo(fields: String) -> Observable<[String: Any]?>

Sets the delegate for a given Facebook login button (with Firebase Authentication)

Declaration

func setDelegate(
    for button: FBLoginButton,
    fields: String,
    loginCompletion: ((Result<(AuthDataResult, [String : Any]?), Error>) -> Void)? = nil,
    logoutCompletion: ((Error?) -> Void)? = nil
)

Parameters

  • button: An instance of the FBLoginButton class that represents the button on which the delegate is set.

  • fields: A comma-separated string of fields to be returned in the response from Facebook’s Graph API. (Reference)

  • loginCompletion: A completion handler that gets called after a successful login and returns the user’s auth data and additional fields.

  • logoutCompletion: A completion handler that gets called after a successful logout and returns any error that might occur.

Discussion

This function sets the delegate for the given button and allows for handling of login and logout events, returns user’s additional fields and also handles the Firebase Authentication. The completion handlers are optional and will only be called if provided.


Sets the delegate for a given Facebook login button

Declaration

func setDelegate(
    for button: FBLoginButton,
    fields: String,
    loginCompletion: ((Result<[String : Any]?, Error>) -> Void)? = nil,
    logoutCompletion: ((Error?) -> Void)? = nil
)

Parameters

  • button: An instance of the FBLoginButton class that represents the button on which the delegate is set.

  • fields: A comma-separated string of fields to be returned in the response from Facebook’s Graph API. (Reference)

  • loginCompletion: A completion handler that gets called after a successful login and returns the user’s auth data and additional fields.

  • logoutCompletion: A completion handler that gets called after a successful logout and returns any error that might occur.

Discussion

This function sets the delegate for the given button and allows for handling of login and logout events, returns user’s additional fields. The completion handlers are optional and will only be called if provided.


Removes the delegate for a given Facebook login button

Declaration

func removeDelegate(for button: FBLoginButton? = nil)

Parameters

button: An instance of the FBLoginButton class that represents the button from which the delegate is to be removed, it is optional and if not provided it will remove the delegate from the current button.

Discussion

This function removes the delegate from the given button and stop handling the login/logout events. This function should be called when the button is no longer needed or when the user is logging out.