Fetch Facebook User Profile Details in Swift

In this tutorial, you will learn how to fetch Facebook user profile details in Swift. First, you’ll implement sign-in with Facebook, and once logged in, you’ll fetch the user’s profile details using the Facebook SDK.

Step 1: Register Your Facebook Developer Account

Before integrating Facebook Login into your app, you must register as a Facebook developer. Here’s how to do it:

  1. Go to the Facebook Developers website.
  2. Click on the “Get Started” button.
  3. Create a new Facebook App ID if you haven’t done so already.
  4. Set up your app details including the name, category, and contact email.
  5. Once your app is created, note down the App ID and App Secret as they will be needed for further configurations.

Step 2: Add Package Dependency

To integrate Facebook Login in your iOS app, you need to add the Facebook SDK as a dependency. Open your project in Xcode and navigate to File > Swift Packages > Add Package Dependency. Enter the Facebook SDK repository URL and follow the prompts to add the package to your project.

Fetch Facebook User Profile Details in Swift

Step 3: Register and Configure Your App with Facebook

After adding the SDK, you need to configure your app within the Facebook Developers portal:

  1. Navigate to the App Dashboard on the Facebook Developers site.
  2. Under the “Add Product” section, click on “Set Up” next to Facebook Login.
  3. Fill in the required fields, such as the bundle ID of your iOS app and the class name of your app delegate.
  4. Save changes to apply the configuration.

Step 4: Add Configuration to Info.plist

Update your Info.plist file with the Facebook App ID and other relevant information:

  • Right-click Info.plist, and choose Open As ▸ Source Code.
  • Copy and paste the following XML snippet into the body of your file ( <dict>...</dict>)
<key>CFBundleURLTypes</key>
<array>
  <dict>
  <key>CFBundleURLSchemes</key>
  <array>
    <string>fbAPP-ID</string>
  </array>
  </dict>
</array>
<key>FacebookAppID</key>
<string>APP-ID</string>
<key>FacebookClientToken</key>
<string>CLIENT-TOKEN</string>
<key>FacebookDisplayName</key>
<string>APP-NAME</string>

<key>LSApplicationQueriesSchemes</key>
<array>
  <string>fbapi</string>
  <string>fb-messenger-share-api</string>
</array>
  • In <array><string> in the key [CFBundleURLSchemes], replace APP-ID with your App ID.
  • In <string> in the key FacebookAppID, replace APP-ID with your App ID.
  • In <string> in the key FacebookClientToken, replace CLIENT-TOKEN with the value found under Settings > Advanced > Client Token in your App Dashboard.
  • In <string> in the key FacebookDisplayName, replace APP-NAME with the name of your app.

Step 5: Enable Keychain Sharing

The Facebook SDK uses the Keychain to securely store user tokens and sensitive information. Without Keychain Sharing enabled, the SDK can’t securely store these details, leading to potential security issues and SDK malfunctions. To enable keychain sharing:

  1. Select your project in Xcode and go to Target > Capabilities.
  2. Turn on Keychain Sharing and ensure the Keychain Groups are correctly set.

Step 6: Configure App Delegate

Modify your AppDelegate.swift to handle the Facebook SDK’s responses:

func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    return ApplicationDelegate.shared.application(app, open: url, options: options)
}

Step 7: Add Facebook Login Button

Now, you create a Facebook Login button and add the necessary permissions permissions that the app is requesting from the user. Bellow code you are requesting for “public_profile” permission. It allows your app to access the user’s public profile. Finally, you add the Facebook Login button to your view controller:

// Instantiate the Facebook Login button provided by the SDK
let loginButton = FBLoginButton()

// Position the button at the center of the view
loginButton.center = view.center

// Assign the current view controller as the delegate to handle login events
// The delegate must conform to the LoginButtonDelegate protocol
loginButton.delegate = self

// Specify the permissions that the app is requesting from the user
// "public_profile" permission allows the app to access the user's public profile
loginButton.permissions = ["public_profile"]

// Add the login button to the view hierarchy
// This makes the button visible and interactive on the screen
view.addSubview(loginButton)

You can include other permissions like”email”, “user_friends”, etc. But keep in mind some permission needs your Facebook business profile verification.

Step 9: Implement Login and Logout Delegate Methods

Implement the LoginButtonDelegate methods to handle successful login and logout events:

func loginButton(_ loginButton: FBSDKLoginKit.FBLoginButton, didCompleteWith result: FBSDKLoginKit.LoginManagerLoginResult?, error: Error?) {
    print("Login Success")
    getCurrentUser(token: result!.token!.tokenString)
}

func loginButtonDidLogOut(_ loginButton: FBSDKLoginKit.FBLoginButton) {
    print("Logout Success")
}

Step 10: Check Current Login Status

Check if the user is currently logged in and fetch their profile information using the user token:

if let token = AccessToken.current, !token.isExpired {
    getCurrentUser(token: token.tokenString)
}

Step 11: Fetch User Data

You can make a Graph API request to fetch user data:

func getCurrentUser(token: String) {
    let request = FBSDKLoginKit.GraphRequest(
        graphPath: "me",
        parameters: ["fields": "name, picture.width(720).height(720)"], // You can add your necessary parameters
        tokenString: token,
        version: nil,
        httpMethod: .get
    )
    
    request.start(completion: { connection, result, error in
        print(result as Any)
    })
}

When requesting any data, make sure you have the necessary permission, which you requested in step 7 of this tutorial.

Complete Code Example

Here is the complete code for the ViewController:

import UIKit
import FacebookLogin

class ViewController: UIViewController, LoginButtonDelegate {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        view.backgroundColor = .white
        
        let loginButton = FBLoginButton()
        loginButton.center = view.center
        loginButton.delegate = self
        loginButton.permissions = ["public_profile"]
        view.addSubview(loginButton)
        
        if let token = AccessToken.current,
           !token.isExpired {
            getCurrentUser(token: token.tokenString)
        }
    }
    
    func getCurrentUser(token: String) {
        let request = FBSDKLoginKit.GraphRequest(
            graphPath: "me",
            parameters: ["fields": "name, picture.width(720).height(720)"],
            tokenString: token,
            version: nil,
            httpMethod: .get
        )
        
        request.start(completion: { connection, result, error in
            print(result as Any)
        })
    }
    
    func loginButton(_ loginButton: FBSDKLoginKit.FBLoginButton, didCompleteWith result: FBSDKLoginKit.LoginManagerLoginResult?, error: Error?) {
        print("Login Success")
        getCurrentUser(token: result!.token!.tokenString)
    }
    
    func loginButtonDidLogOut(_ loginButton: FBSDKLoginKit.FBLoginButton) {
        // This function is called when the user logs out from Facebook using the login button provided by the SDK.
        print("Logout Success")
    }
}

Fetch Facebook User Profile Details in Swift

Conclusion

Now, you have successfully integrated Facebook Login into your iOS app. Remember to test your implementation thoroughly, ensuring that users can log in and out, and that their information is retrieved correctly.

To learn more about Swift and to find other code examples, check the following page: Swift Code Examples.

Keep coding, and happy learning!