Fetch Facebook User Profile Details in Swift

In this short Swift code example we will use FBSDKGraphRequest from Facebook iOS SDK to fetch user profile details. The code example on this page will cover:

  • Import FBSDKCoreKit and FBSDKLoginKit
  • Get Facebook access token with FBSDKAccessToken.currentAccessToken()
  • Use FBSDKGraphRequest to fetch Facebook user profile details including email address and profile picture
  • Display Facebook user full name
  • Display Facebook user profile picture
  • Print to Xcode console entire fetched Facebook user profile object

For the code below to work user needs to be logged in with their Facebook profile. To let user login into your app with their Facebook account and for your app be able to fetch their public profile details and email address, use the code snipped below:

Facebook Login Button and Profile Read Permissions – Swift Code Example.

 
       let button = FBSDKLoginButton()
        button.center = view.center
        button.readPermissions = ["public_profile","email"]
        self.view.addSubview(button)

Fetch Facebook User Profile Details – Swift Code Example

  
 
import UIKit
import FBSDKCoreKit
import FBSDKLoginKit

class FetchUserProfileController: UIViewController {
    
    @IBOutlet weak var userFullName: UILabel!
    @IBOutlet weak var userProfileImage: UIImageView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        userFullName.text = ""
        
        if let _ = FBSDKAccessToken.currentAccessToken()
        {
            fetchUserProfile()
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    
    
    func fetchUserProfile()
    {
        let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"id, email, name, picture.width(480).height(480)"])
        
        graphRequest.startWithCompletionHandler({ (connection, result, error) -> Void in
            
            if ((error) != nil)
            {
                print("Error took place: \(error)")
            }
            else
            {
                print("Print entire fetched result: \(result)")
                
                let id : NSString = result.valueForKey("id") as! String
                print("User ID is: \(id)")
                
                if let userName = result.valueForKey("name") as? String
                {
                    self.userFullName.text = userName
                }
                
                if let profilePictureObj = result.valueForKey("picture") as? NSDictionary
                {
                    let data = profilePictureObj.valueForKey("data") as! NSDictionary
                    let pictureUrlString  = data.valueForKey("url") as! String
                    let pictureUrl = NSURL(string: pictureUrlString)
                    
                    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)) {
                        
                        let imageData = NSData(contentsOfURL: pictureUrl!)
                        
                        dispatch_async(dispatch_get_main_queue()) {
                            if let imageData = imageData
                            {
                                let userProfileImage = UIImage(data: imageData)
                                self.userProfileImage.image = userProfileImage
                                self.userProfileImage.contentMode = UIViewContentMode.ScaleAspectFit
                            }
                        }
                    }
                }
            }
        })
    }
 
}

 

Checkout more Swift code examples at Swift Code Examples page.


Learn iOS Development with these Video Courses

The Complete iOS 11 & Swift Developer Course - Build 20 Apps

Use Xcode 9 & Swift 4 to make real apps like Uber and Instagram, with CoreML & ARKit. Includes AWS Credit and much more. Preview this video course. icon

How to Make a Freaking iPhone App - iOS 11 and Swift 4

iPhone App Development from scratch. Learn how to make iOS apps using Xcode 9. The Basics Include Pokemon Go & Snapchat. Learn to build iOS Apps with Xcode 9 and Swift 4. How to Make a Freaking iPhone App - iOS 11 and Swift 4 icon

iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course

A Complete iOS 11 and Xcode 9 Course with Swift 4 & Objective-C. Preview this video course. iOS 11 and Xcode 9 - Complete Swift 4 & Objective-C Course icon