Facebook friends list api for swift ios - ios

I have tried to get the facebook friends list for an IOS app, but receiving empty response from facebook.
How to get face book friends list in swift?

In Graph API v2.0 or above, calling /me/friends returns the person's friends who installed the same apps. Additionally, 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.
To get the list of friends who are using your app use following code:
let params = ["fields": "id, first_name, last_name, middle_name, name, email, picture"]
let request = FBSDKGraphRequest(graphPath: "me/friends", parameters: params)
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error != nil {
let errorMessage = error.localizedDescription
/* Handle error */
}
else if result.isKindOfClass(NSDictionary){
/* handle response */
}
}
If you want to access a list of non-app-using friends, then use following code:
let params = ["fields": "id, first_name, last_name, middle_name, name, email, picture"]
let request = FBSDKGraphRequest(graphPath: "me/taggable_friends", parameters: params)
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error != nil {
let errorMessage = error.localizedDescription
}
else if result.isKindOfClass(NSDictionary){
/* Handle response */
}
}

For fetching the friend list must allow user permission user_friends at the time of login.
For swift 3.0 add below code for fetching friend list:
let params = ["fields": "id, first_name, last_name, middle_name, name, email, picture"]
FBSDKGraphRequest(graphPath: "me/taggable_friends", parameters: params).start { (connection, result , error) -> Void in
if error != nil {
print(error!)
}
else {
print(result!)
//Do further work with response
}
}
I hope it works!

Remember only those friends are fetched who are using your app and u should have taken users read permission for user_friends while logging.
var fbRequest = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil);
fbRequest.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
println("Friends are : \(result)")
} else {
println("Error Getting Friends \(error)");
}
}
Refer to : https://developers.facebook.com/docs/graph-api/reference/v2.3/user/friends#read

Just making an union here that solved my problems:
From Dheeraj Singh, to get friends using your app:
var request = FBSDKGraphRequest(graphPath:"/me/friends", parameters: nil);
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
println("Friends are : \(result)")
} else {
println("Error Getting Friends \(error)");
}
}
And to get all facebook friends, from Meghs Dhameliya, ported to swift:
var request = FBSDKGraphRequest(graphPath:"/me/taggable_friends", parameters: nil);
request.startWithCompletionHandler { (connection : FBSDKGraphRequestConnection!, result : AnyObject!, error : NSError!) -> Void in
if error == nil {
println("Friends are : \(result)")
} else {
println("Error Getting Friends \(error)");
}
}

you can get friend list using taggable_friends
Graph API Reference for User Taggable Friend
/* make the API call */
[FBRequestConnection startWithGraphPath:#"/me/taggable_friends"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
/* handle the result */
}];

Swift - 4
This will only return your facebook friends using the same app.
// First you have to check that `user_friends` has associated with your `Access Token`, If you are getting false, please allow allow this field while you login through facebook.
if FBSDKAccessToken.current().hasGranted("user_friends") {
// Prepare your request
let request = FBSDKGraphRequest.init(graphPath: "me/friends", parameters: params, httpMethod: "GET")
// Make a call using request
let _ = request?.start(completionHandler: { (connection, result, error) in
print("Friends Result: \(String(describing: result))")
})
}

With user_friends permission you can have access to the list of your friends that also use your app, so if your app is not used by any of your friend, the list will be empty. See user_friends permission reference

Related

can i get user name from Facebook api? , I need user name to use [duplicate]

This question already has answers here:
How to get username from Facebook SDK 4.0 in ios
(4 answers)
Closed 4 years ago.
Hi I just use this api for getting user details but I can't get user name please help me
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"id,first_name,last_name,gender,email,picture.type(large),groups" forKey:#"fields"]]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (error==nil) {
}else {
NSLog(#"facebook erro : %# ",error);
}
}];
You need to ask permissions to access data which is not public.
Check the blog here, it mentions how to request permission for private data.
This is a snippet from the above blog
let loginManager = FBSDKLoginManager()
let permissions = ["public_profile", "email","username"] //not sure username is to be used or user_name.
let handler = loginManager.logInWithReadPermissions(permissions, fromViewController: self, handler: handler)
After the user grants access to his private data. You will be able to retrieve the data.
Facebook iOS sdk get user name and email in swift 3 -
FBSDKGraphRequest(graphPath: "me", parameters: ["fields": "id, name, first_name, last_name, email"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
let fbDetails = result as! NSDictionary
print(fbDetails)
}else{
print(error?.localizedDescription ?? "Not found")
}
})

How to access user_location in Facebook Login?

I'm requesting the permissions like this:
fbLoginManager.logIn(withReadPermissions: ["public_profile", "email", "user_friends", "user_location"], from: self) { (result, error) in
Upon signup I can see it is asking me for the user_location:
let request = FBSDKGraphRequest(graphPath: "me", parameters: ["fields":"first_name, last_name, user_location"], httpMethod: "GET")
request?.start(completionHandler: { (connection, result, error) -> Void in
if ((error) != nil)
{
// Process error
print("Error: \(String(describing: error))")
}
else
{
print(result!)
}
let data:[String:AnyObject] = result as! [String : AnyObject]
})
But it seems the key is missing:
Error: Optional(Error Domain=com.facebook.sdk.core Code=8 "(null)" UserInfo={com.facebook.sdk:FBSDKGraphRequestErrorCategoryKey=0, com.facebook.sdk:FBSDKGraphRequestErrorHTTPStatusCodeKey=400, com.facebook.sdk:FBSDKErrorDeveloperMessageKey=(#100) Tried accessing nonexisting field (user_location) on node type (User), com.facebook.sdk:FBSDKGraphRequestErrorGraphErrorCode=100, com.facebook.sdk:FBSDKGraphRequestErrorParsedJSONResponseKey={
body = {
error = {
code = 100;
"fbtrace_id" = Hp3weSaqfI7;
message = "(#100) Tried accessing nonexisting field (user_location) on node type (User)";
type = OAuthException;
};
};
code = 400;
}})
fatal error: unexpectedly found nil while unwrapping an Optional value
But according to the docs, it should be on the user object. Thanks
But according to the docs, it should be on the user object.
No, it should not.
You are confusing the name of the permission - user_location - with the name of the actual field of the user object - location.
https://developers.facebook.com/docs/graph-api/reference/user/:
location
Page
The person's current location as entered by them on their profile. This field is not related to check-ins

Facebook Graph API mutual friends images

I'm able to retrieve users' mutual friends using context.fields(mutual_friends)but I need to display images of the friends. However, I'm only getting back the friends id and name only. Is it possible to retrieve their images in the same call?
if((FBSDKAccessToken.current()) != nil){
FBSDKGraphRequest(graphPath: "/\(userID)", parameters: ["fields": "context.fields(mutual_friends)"]).start(completionHandler: { (connection, result, error) -> Void in
if (error == nil){
print("//////Mutual friends")
print(result!)
} else {
print(error!.localizedDescription)
}
})
}
You can get the image with using this API
https://graph.facebook.com/(friendFacebookId)/picture?type=large
For more info check this

Facebook Friends List Swift

I am trying to run a function to see Facebook friends so users can see which are currently using the app. I have done some researching and found some older code but nothing that works with Swift 3. Here is what I have right now:
var fbRequestFriends: FBSDKGraphRequest = FBSDKGraphRequest.requestForMyFriends()
fbRequestFriends.startWithCompletionHandler{
(connection:FBSDKGraphRequestConnection!,result:AnyObject?, error:NSError!) -> Void in
if error == nil && result != nil {
print("Request Friends result : \(result!)")
} else {
print("Error \(error)")
}
}
It will not run because FBSDKGraphRequest does not have a requestForMyFriends. Does anyone know how to update this in order to work on swift 3?
I have also found this on Facebook Docs but it is all in Obj C but am having issues converting it:
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/{friend-list-id}"
parameters:params
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
// Handle the result
}];
Code that you looking for is:
var fbRequestFriends: FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "/{friend-list-id}", parameters: [AnyHashable : Any]())
fbRequestFriends.start { (connection, result, error) in
if error == nil && result != nil {
print("Request Friends result : \(result!)")
} else {
print("Error \(error)")
}
}
It will execute the request, I do not guarantee that it will work for various reasons, for example - you need permission to ask for a friends list.

Trouble retrieving list of facebook friends from json data in swift

I am using FBSDK in my Swift iOS application and currently I am trying to retrieve the list of friends who also use my app. I have two-three people who should show up but whenever I search the graphrequest result for friends it returns nil..
let graphRequest : FBSDKGraphRequest = FBSDKGraphRequest(graphPath: "me", parameters: nil)
graphRequest.startWithCompletionHandler({ (connection, result:AnyObject!, error) -> Void in
if ((error) != nil)
{
// Process error
println("Error: \(error)")
}
else
{
//get Facebook ID
let faceBookID: NSString = result.valueForKey("id") as NSString
//get username
let userName : NSString = result.valueForKey("name") as NSString
//get facebook friends who use app
let friendlist: AnyObject = result.valueForKey("friends") as AnyObject
}
I have the "email", "user_friends", and "public_profile" permissions which should be enough to retrieve this information. Any Ideas on what I am doing wrong?? this is doing my head in as my friend doing an android version has successfully got his working..
My problem here was that I never Actually requested for the list of friends in my facebook graph request...
after replacing FBSDKGraphRequest(graphPath: "me", parameters: nil)
with FBSDKGraphRequest(graphPath: "me?fields=id,name,friends", parameters: nil)
I was able to retrieve the list of friends because the response actually contained information for this. A very trivial mistake on my part.
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.
see here : https://developers.facebook.com/bugs/1502515636638396/

Resources