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.
[raw_html_snippet id=”cookbookpagecoursesheader”]
Unit Testing Swift Mobile App
Apply Test-Driven Development(TDD) process to iOS mobile app development in Swift Preview this video course.