How to login in ur app by facebook
Categories:
Integrate Facebook Login into Your iOS App
Learn how to seamlessly add Facebook Login to your iOS application, enabling users to sign in quickly and securely using their Facebook accounts.
Integrating Facebook Login into your iOS application provides a convenient and familiar authentication method for your users. This guide will walk you through the necessary steps, from setting up your Facebook Developer account to implementing the login flow in your Xcode project. By the end, your app will be able to authenticate users via Facebook, enhancing user experience and simplifying the onboarding process.
1. Facebook Developer Setup
Before you can integrate Facebook Login, you need to set up your application on the Facebook Developer Portal. This involves creating a new app, configuring its basic settings, and enabling the Facebook Login product.
1. Create a Facebook Developer Account
If you don't already have one, navigate to the Facebook for Developers website and create an account. You'll need to verify your identity.
2. Create a New App
From the Facebook Developer dashboard, click 'My Apps' -> 'Create App'. Choose the 'Consumer' type for most mobile applications and follow the prompts to name your app and provide contact email.
3. Add Facebook Login Product
Once your app is created, go to the app dashboard. In the left-hand navigation, under 'Products', click the '+' icon and select 'Facebook Login'. Click 'Set Up'.
4. Configure Quickstart for iOS
After adding Facebook Login, select 'iOS' from the Quickstart options. You'll be guided to provide your Bundle ID (found in Xcode under your project's General settings) and enable 'Single Sign On' if desired. Make sure to save your changes.
2. Xcode Project Configuration
With your Facebook app configured, the next step is to integrate the Facebook SDK into your iOS project and set up the necessary configurations in Xcode.
1. Install Facebook SDK via CocoaPods
Open your project's Podfile
and add the following lines. Then run pod install
in your terminal. This installs the core Facebook SDK and the LoginKit.
2. Update Info.plist
Add the required keys to your Info.plist
file. This includes your Facebook App ID, Display Name, and URL Schemes. Replace YOUR_APP_ID
and YOUR_APP_NAME
with your actual values.
3. Configure SceneDelegate/AppDelegate
Initialize the Facebook SDK and handle URL callbacks. If your app uses SceneDelegate
, implement the scene(_:openURLContexts:)
method. For older apps using AppDelegate
, use application(_:open:options:)
.
platform :ios, '13.0'
target 'YourAppName' do
use_frameworks!
pod 'FacebookCore'
pod 'FacebookLogin'
end
Example Podfile configuration for Facebook SDK
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fbYOUR_APP_ID</string>
</array>
</dict>
</array>
<key>FacebookAppID</key>
<string>YOUR_APP_ID</string>
<key>FacebookDisplayName</key>
<string>YOUR_APP_NAME</string>
<key>LSApplicationQueriesSchemes</key>
<array>
<string>fbapi</string>
<string>fb-messenger-share-api</string>
<string>fbauth2</string>
<string>fbshareextension</string>
</array>
Required Info.plist
entries for Facebook Login
// In SceneDelegate.swift
import FacebookCore
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {
guard let url = URLContexts.first?.url else { return }
ApplicationDelegate.shared.application(
UIApplication.shared,
open: url,
sourceApplication: nil,
annotation: [UIApplication.OpenURLOptionsKey.annotation]
)
}
// In AppDelegate.swift (if not using SceneDelegate)
import FacebookCore
func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
) -> Bool {
ApplicationDelegate.shared.application(
application,
didFinishLaunchingWithOptions: launchOptions
)
return true
}
func application(
_ app: UIApplication,
open url: URL,
options: [UIApplication.OpenURLOptionsKey : Any] = [:]
) -> Bool {
ApplicationDelegate.shared.application(
app,
open: url,
sourceApplication: options[UIApplication.OpenURLOptionsKey.sourceApplication] as? String,
annotation: options[UIApplication.OpenURLOptionsKey.annotation]
)
}
Handling URL callbacks in SceneDelegate or AppDelegate
3. Implementing the Login Flow
Now that the setup is complete, you can add the Facebook Login button and handle the authentication process in your view controller.
sequenceDiagram participant User participant App participant FacebookSDK participant FacebookServer User->>App: Taps 'Login with Facebook' App->>FacebookSDK: Request login with permissions FacebookSDK->>FacebookServer: Authenticate user (via Safari/Facebook App) FacebookServer-->>FacebookSDK: Returns access token or error FacebookSDK-->>App: Provides login result (success/failure) alt Login Successful App->>App: Store access token App->>User: User logged in else Login Failed App->>User: Show error message end
Sequence diagram of the Facebook Login process
import UIKit
import FacebookLogin
import FacebookCore
class LoginViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
setupFacebookLoginButton()
}
func setupFacebookLoginButton() {
let loginButton = FBLoginButton(permissions: [.publicProfile, .email])
loginButton.center = view.center
view.addSubview(loginButton)
loginButton.delegate = self
}
}
extension LoginViewController: LoginButtonDelegate {
func loginButton(_ loginButton: FBLoginButton, didCompleteWith result: LoginManagerLoginResult?, error: Error?) {
if let error = error {
print("Facebook Login Error: \(error.localizedDescription)")
// Handle error (e.g., show alert to user)
return
}
guard let result = result else { return }
if result.isCancelled {
print("Facebook Login Cancelled")
return
}
if let token = result.token {
print("Facebook Access Token: \(token.tokenString)")
// Successfully logged in, navigate to main app content
// You can also fetch user profile data here using Graph API
fetchUserProfile()
}
}
func loginButtonDidLogOut(_ loginButton: FBLoginButton) {
print("User logged out of Facebook")
// Handle logout (e.g., clear user session, navigate to login screen)
}
func fetchUserProfile() {
GraphRequest(graphPath: "me", parameters: ["fields": "id, name, email, picture.type(large)"]).start { connection, result, error in
if let error = error {
print("Graph API Error: \(error.localizedDescription)")
return
}
switch result {
case .success(let graphResponse):
if let responseDictionary = graphResponse.dictionaryValue {
print("User Profile: \(responseDictionary)")
// Parse user data and proceed
}
case .failure(let error):
print("Graph API Failure: \(error.localizedDescription)")
default:
break
}
}
}
}
Implementing Facebook Login in a Swift ViewController