Note: Newer tutorial available. If you would like to learn how to implement FBSDKGraphRequest using Facebook SDK 4.0 using Swift, read Tutorial: How To Use Login in Facebook SDK 4.0 for Swift
You’ve probably noticed that most successful games contain a Facebook Leaderboard so users can compete against their friends. You can read more about Game Strategy: Make It Social in one of my previous posts.
Below is a tutorial to help you access the users friends list using the latest Facebook SDK and Graph API in Swift.
Get Friends Using Facebook Graph API v2.0
- Visit the Getting Started with the Facebook iOS SDK documentation to download the Facebook SDK and install it.
- Read and implement my previous post Tutorial: Facebook Login in Swift using a Bridging Header to handle the Facebook Login into your app using Swift.
- In v2.0 of the Graph API, you must request the user_friends permission from each user. user_friends is no longer included by default in every login. Each user must grant the user_friends permission in order to appear in the response to /me/friends.
- Apps are no longer able to retrieve the full list of a user’s friends (only those friends who have specifically authorized your app using the user_friends permission). This has been confirmed by Facebook as ‘by design’.
- Use the following piece of code to get the list of the users friends. This can be used anywhere within your app as long as the user has an active logged in session.
// Get List Of Friends var friendsRequest : FBRequest = FBRequest.requestForMyFriends() friendsRequest.startWithCompletionHandler{(connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in var resultdict = result as NSDictionary println("Result Dict: \(resultdict)") var data : NSArray = resultdict.objectForKey("data") as NSArray for i in 0..<data.count { let valueDict : NSDictionary = data[i] as NSDictionary let id = valueDict.objectForKey("id") as String println("the id value is \(id)") } var friends = resultdict.objectForKey("data") as NSArray println("Found \(friends.count) friends") }
- If successful you’ll be returned an NSDictionary in JSON with an array of data that contains the basic data for each of the users friends who use your app. Note: Be sure to test using another Facebook account that is friends with your account.
Result Dict: { data = ( { "first_name" = Brian; id =
; "last_name" = Coleman; name = "Brian Coleman"; } ); paging = { next = "https://graph.facebook.com/v2.0/ /friends?fields=id,name,first_name,last_name&format=json&access_token= &offset=5000&__after_id= "; }; summary = { "total_count" = 1; }; } the id value is Found 1 friends - The next step is to use the list of Facebook user id’s returned in the JSON and populate them into an array so you can compare those user id’s with the user scores in your database, then display that subset of scores in a table view leaderboard.