-
Notifications
You must be signed in to change notification settings - Fork 0
FacebookAuth
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.
- Login Facebook and Firebase Authentication
- Login Facebook
- Logout Facebook and Firebase Authentication
- Get the Facebook Access Token of the currently logged-in user
- Fetches the user's information from Facebook
- Sets the delegate for a given Facebook login button (with Firebase Authentication)
- Sets the delegate for a given Facebook login button
- Removes the delegate for a given Facebook login button
- iOS 13 and above
- Swift 5.7 and above
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.
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.
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")
}
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)
}
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
func login(
permissions: [Permission],
fields: String,
viewController: UIViewController?,
completion: ((Result<(AuthDataResult, [String : Any]?), Error>) -> Void)? = nil
)
-
permissions
: An array ofPermission
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 optionalUIViewController
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 aResult
object, which contains either anAuthDataResult
object and a dictionary of the fields returned for the user, or an error if the login failed.
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.
// 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]?)>
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
func login(
permissions: [Permission],
fields: String,
viewController: UIViewController?,
completion: ((Result<[String : Any]?, Error>) -> Void)? = nil
)
-
permissions
: An array ofPermission
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 optionalUIViewController
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 typeResult<[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.
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.
// 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]?>
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
func logout() -> Error?
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.
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.
sequenceDiagram
participant iOSApp
alt token exists
iOSApp->>iOSApp: returns Facebook token
else token not exists
iOSApp->>iOSApp: returns nil
end
func getAccessToken() -> AccessToken?
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
.
This function is used to retrieve the user’s access token. The function should be called when the user is logged in successfully.
sequenceDiagram
participant iOSApp
participant Facebook
iOSApp->>+Facebook: Request: get-user-info
Facebook-->>-iOSApp: OK(user info)
iOSApp->>iOSApp: returns user info
func getUserInfo(
fields: String,
completion: @escaping (Result<[String : Any]?, Error>) -> Void
)
-
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.
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.
// 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]?>
func setDelegate(
for button: FBLoginButton,
fields: String,
loginCompletion: ((Result<(AuthDataResult, [String : Any]?), Error>) -> Void)? = nil,
logoutCompletion: ((Error?) -> Void)? = nil
)
-
button
: An instance of theFBLoginButton
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.
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.
func setDelegate(
for button: FBLoginButton,
fields: String,
loginCompletion: ((Result<[String : Any]?, Error>) -> Void)? = nil,
logoutCompletion: ((Error?) -> Void)? = nil
)
-
button
: An instance of theFBLoginButton
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.
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.
func removeDelegate(for button: FBLoginButton? = nil)
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.
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.