getting friends list and photos of facebook with ios - ios

Using the facebook ios sdk, how can I get an NSArray of all my friends list with their photos?
FBLoginView *loginView = [[FBLoginView alloc] initWithReadPermissions:
#[#"public_profile", #"email", #"read_friendlists"]];
loginView.delegate = self;
loginView.frame = CGRectOffset(loginView.frame, (self.view.center.x - (loginView.frame.size.width / 2)), 250);
[self.view addSubview:loginView];

You can do this by doing an fql request
With the iOS Facebook sdk you can an request like this:
- (IBAction)queryButtonAction:(id)sender {
// Query to fetch the active user's friends, limit to 25.
NSString *query =
#"SELECT uid, name, pic_square FROM user WHERE uid IN "
#"(SELECT uid2 FROM friend WHERE uid1 = me() LIMIT 25)";
// Set up the query parameter
NSDictionary *queryParam = #{ #"q": query };
// Make the API request that uses FQL
[FBRequestConnection startWithGraphPath:#"/fql"
parameters:queryParam
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (error) {
NSLog(#"Error: %#", [error localizedDescription]);
} else {
NSLog(#"Result: %#", result);
}
}];
}
This is an example taken from here: https://developers.facebook.com/docs/ios/graph#fql
Read more about this here:
https://developers.facebook.com/docs/ios/graph
The friendlist is documented here:
https://developers.facebook.com/docs/reference/fql/friendlist/

Related

How get list of friends and email using Facebook sdk

I have a problem i implement Facebook SDK in my view controller and want to get list of friends and email using Facebook. I wrote this:
FBLoginView *loginView = [[FBLoginView alloc] initWithReadPermissions:#[#"public_profile", #"email", #"user_friends"]];
loginView.delegate = self;
and then use the protocol method of FBLoginViewDelegate:
- (void)loginViewFetchedUserInfo:(FBLoginView *)loginView
user:(id<FBGraphUser>)user
{
self.profilePictureView.profileID = user.id;
self.nameLabel.text = user.name;
NSLog(#"%#", user);
NSLog(#"%#", [user objectForKey:#"email"]);
}
In console i got this:
2014-12-04 14:56:48.746 FBLoginUIControlSample[2941:613]
"first_name" = Pavel;
gender = male;
id = 1379600000000000;
"last_name" = name;
link = "https://www.facebook.com/app_scoped_user_id/1379600000000000/";
locale = "ru_RU";
name = "Pavel name";
timezone = 2;
"updated_time" = "2014-12-03T11:47:13+0000";
verified = 1;
2014-12-04 14:56:48.748 FBLoginUIControlSample[2941:613] (null)
sorry , but you can't
Read Facebook Permissions
you only can get the email when the user login , but you can't get user's friends email.
i am not really sure but maybe you can use "friendsusername"#facebook.com ("facebook email").
i found this, https://www.facebook.com/help/224049364288051
the person has to active #facebook option.
For friends with Facebook SDK 3.0 you can do this
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
NSLog(#"Found: %i friends", friends.count);
for (NSDictionary<FBGraphUser>* friend in friends) {
NSLog(#"I have a friend named %# with id %#", friend.name, friend.id);
}
}];
You can not access to any users email, excepts of yours.
Because FBGraphUser doesn't have an email #property, we can't access the information like with the name (dot-syntax), however the NSDictionary still has the email kv-pair and we can access it like we would do with a normal NSDictionary.
With this method you can access to your email.
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
self.nameLabel.text = user.name;
self.emailLabel.text = [user objectForKey:#"email"];
}
}];
}
hope this will help you
you can get your friend list by using below code in your viewDidLoad
[FBRequestConnection startWithGraphPath:#"me/taggable_friends"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
}];
and some info
EDIT
the above answer only mention for friendlist not email(as its already quite clear by above answers) , now what you want friendlist
A friend list(Friend List V 2.2) - an object which refers to a grouping of friends created by someone or generated automatically for someone (such as the "Close Friends" or "Acquaintances" lists)
from v2.0 you'll only be able to get all friends via the /me/taggable_friends (see it by result)

How to get Friends list from Facebook iOS sdk

I am using iOS sdk v3.18.1, I want to get all my Facebook friends.I can get the friends count but, data is nil.
Here is my code
[FBRequestConnection startWithGraphPath:#"me/friends" parameters:nil HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"result %#",result);
}];
Out put
{
data = (
);
summary = {
"total_count" = 840;
};
}
https://developers.facebook.com/docs/apps/changelog
Since v2.0 you cannot get the full friend list anymore, you only get the friends who authorized your App too.
See my answer in this thread too: how to get a list of all user friends (not only who use the app)?
// declare an array in header file which will hold the list of all friends -
NSMutableArray * m_allFriends;
// alloc and initialize the array only once
m_allFriends = [[NSMutableArray alloc] init];
With FB SDK 3.0 and API Version above 2.0 you need to call below function (graph api with me/friends)to get list of FB Friends which uses the same app.
// get friends which use the app
-(void) getMineFriends
{
[FBRequestConnection startWithGraphPath:#"me/friends"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
NSLog(#"me/friends result=%#",result);
NSLog(#"me/friends error = %#", error.description);
NSArray *friendList = [result objectForKey:#"data"];
[m_allFriends addObjectsFromArray: friendList];
}];
}
Note : 1) The default limit for the number of friends returned by above query is 25. 2)If the next link comes in result, that means there are some more friends which you will be fetching in next query and so on. 3)Alternatively you can change the limit (reduce the limit, exceed the limit from 25) and pass that in param.
////////////////////////////////////////////////////////////////////////
For non app friends -
// m_invitableFriends - global array which will hold the list of invitable friends
Also to get non app friends you need to use (/me/invitable_friends) as below -
- (void) getAllInvitableFriends
{
NSMutableArray *tempFriendsList = [[NSMutableArray alloc] init];
NSDictionary *limitParam = [NSDictionary dictionaryWithObjectsAndKeys:#"100", #"limit", nil];
[self getAllInvitableFriendsFromFB:limitParam addInList:tempFriendsList];
}
- (void) getAllInvitableFriendsFromFB:(NSDictionary*)parameters
addInList:(NSMutableArray *)tempFriendsList
{
[FBRequestConnection startWithGraphPath:#"/me/invitable_friends"
parameters:parameters
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
NSLog(#"error=%#",error);
NSLog(#"result=%#",result);
NSArray *friendArray = [result objectForKey:#"data"];
[tempFriendsList addObjectsFromArray:friendArray];
NSDictionary *paging = [result objectForKey:#"paging"];
NSString *next = nil;
next = [paging objectForKey:#"next"];
if(next != nil)
{
NSDictionary *cursor = [paging objectForKey:#"cursors"];
NSString *after = [cursor objectForKey:#"after"];
//NSString *before = [cursor objectForKey:#"before"];
NSDictionary *limitParam = [NSDictionary dictionaryWithObjectsAndKeys:
#"100", #"limit", after, #"after"
, nil
];
[self getAllInvitableFriendsFromFB:limitParam addInList:tempFriendsList];
}
else
{
[self replaceGlobalListWithRecentData:tempFriendsList];
}
}];
}
- (void) replaceGlobalListWithRecentData:(NSMutableArray *)tempFriendsList
{
// replace global from received list
[m_invitableFriends removeAllObjects];
[m_invitableFriends addObjectsFromArray:tempFriendsList];
//NSLog(#"friendsList = %d", [m_invitableFriends count]);
[tempFriendsList release];
}
For Inviting non app friend -
you will get invite tokens with the list of friends returned by me/invitable_friends graph api. You can use these invite tokens with FBWebDialogs to send invite to friends as below
- (void) openFacebookFeedDialogForFriend:(NSString *)userInviteTokens {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
userInviteTokens, #"to",
nil, #"object_id",
#"send", #"action_type",
actionLinksStr, #"actions",
nil];
[FBWebDialogs
presentRequestsDialogModallyWithSession:nil
message:#"Hi friend, I am playing game. Come and play this awesome game with me."
title:nil
parameters:params
handler:^(
FBWebDialogResult result,
NSURL *url,
NSError *error)
{
if (error) {
// Error launching the dialog or sending the request.
NSLog(#"Error sending request : %#", error.description);
}
else
{
if (result == FBWebDialogResultDialogNotCompleted)
{
// User clicked the "x" icon
NSLog(#"User canceled request.");
NSLog(#"Friend post dialog not complete, error: %#", error.description);
}
else
{
NSDictionary *resultParams = [g_mainApp->m_appDelegate parseURLParams:[url query]];
if (![resultParams valueForKey:#"request"])
{
// User clicked the Cancel button
NSLog(#"User canceled request.");
}
else
{
NSString *requestID = [resultParams valueForKey:#"request"];
// here you will get the fb id of the friend you invited,
// you can use this id to reward the sender when receiver accepts the request
NSLog(#"Feed post ID: %#", requestID);
NSLog(#"Friend post dialog complete: %#", url);
}
}
}
}];
}
Since, V2.0 of the Graph API, You will only be able to get the list of the friends who are connected with your app. In v2.0 of the Graph API, calling /me/friends returns the person's friends who use the app. Yes it is possible to get the count but accessing the friend list is not possible.
All the release of Facebook SDK after the month of April denies this functionality of getting the whole list of friends.
REFER : SO QUESTION:Facebook graph API returns empty .... FACEBOOK USER GUIDE
This has been confirmed by FACEBOOK.

Facebook Get friends list

I know it have been asked a lot here, but I can't find a proper answer for that.
I am using Facebook SDK v3.18
I simply want to get user friends list and their pictures .
I've tried so far this:
Login:
FBLoginView *loginView =
[[FBLoginView alloc] initWithReadPermissions:
#[#"public_profile", #"email", #"user_friends"]];
// Align the button in the center horizontally
loginView.frame = CGRectOffset(loginView.frame, (self.view.center.x - (loginView.frame.size.width / 2)), (self.view.center.y - (loginView.frame.size.height / 2)));
[self.view addSubview:loginView];
Get user's friends list and their pictures:
[FBRequestConnection startWithGraphPath:#"/me/friends?fields=name,picture"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(
FBRequestConnection *connection,
id result,
NSError *error
) {
/* handle the result */
}];
But the answer is:
{
data = (
);
summary = {
"total_count" = 1216;
};
}
And non for my friends name or pictures are shown :/
Please put some light for me on this.
Thanks in advance!
From the Facebook SDK page, it looks like /me/friends will only return your friends that have logged in and given permission to the same app (i.e. you and your friends need to have permitted your app to use facebook via login).
Did you tried below ?
FBRequest* friendsRequest = [FBRequest requestWithGraphPath:#"me/friends?fields=name" parameters:nil HTTPMethod:#"GET"];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,
NSDictionary* result,
NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
NSLog(#"Found: %i friends", friends.count);
for (NSDictionary<FBGraphUser>* friend in friends) {
NSLog(#"I have a friend named %# with id %#", friend.name, friend.id);
}
NSArray *friendIDs = [friends collect:^id(NSDictionary<FBGraphUser>* friend) {
return friend.id;
}];
}];
Edit:
Please check this post.
Facebook Graph Api v2.0+ - /me/friends returns empty, or only friends who also use my app

FBSession Error validating access token: Session does not match current stored session

I'm trying to use Facebook SDK in my application. My application is using Salesforce SDK to logging with Salesforce and the user can use Facebook to logging in my application.
From Salesforce can take the Facebook access token when the user logs in with Facebook. I use this access token to open a session with the object FBSession.
This is the code that I'm using to open a session:
NSArray *newPermission = [NSArray arrayWithObjects:#"user_friends",#"email", nil];
NSMutableDictionary *tokenInformationDictionary = [NSMutableDictionary new];
tokenInformationDictionary[#"com.facebook.sdk:TokenInformationExpirationDateKey"] = [NSDate dateWithTimeIntervalSinceNow: 3600];;
tokenInformationDictionary[#"com.facebook.sdk:TokenInformationRefreshDateKey"] = [NSDate date];
tokenInformationDictionary[#"com.facebook.sdk:TokenInformationTokenKey"] = fbAccessToken;
tokenInformationDictionary[#"com.facebook.sdk:TokenInformationPermissionsKey"] = newPermission;
tokenInformationDictionary[#"com.facebook.sdk:TokenInformationLoginTypeLoginKey"] = #0;
FBAccessTokenData *accesToken = [FBAccessTokenData createTokenFromDictionary: tokenInformationDictionary];
[[FBSession activeSession] openFromAccessTokenData:accesToken completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
}];
I'm trying to publish links and get my friends list.
To publish I use this code:
NSDictionary *params = #{
#"name" : [NSString stringWithFormat:NSLocalizedString(#"FBNameFormat", nil), [dicRecord objectForKey:#"Name"], [[dicRecord objectForKey:#"Store__r"] objectForKey:#"Name"]],
#"caption" : [NSString stringWithFormat:NSLocalizedString(#"FBCaptionFormat", nil), [dicRecord objectForKey:#"Name"], [[dicRecord objectForKey:#"Store__r"] objectForKey:#"Name"]],
#"description" : NSLocalizedString(#"FBDescription", nil), //#"Welcome to iOS world",
#"picture" : [dicRecord objectForKey:#"Image__c"],
#"link" : [NSString stringWithFormat:NSLocalizedString(#"FBDishUrl", nil), [dicRecord objectForKey:#"Id"]]//a00w000000V0TK9",
};
// Invoke the dialog
[FBWebDialogs presentFeedDialogModallyWithSession:nil parameters:params handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
NSLog(#"Error publishing story.");
//[self.indicator stopAnimating];
} else if (result == FBWebDialogResultDialogCompleted){
if ([isSuggested isEqual:[NSNumber numberWithInt:-1]]){
NSMutableDictionary *diccionario = [[NSMutableDictionary alloc] init];
}
}
}];
1)
That only works if I close and open again my apps, using
[FBSession.activeSession closeAndClearTokenInformation];
in completionHandler of openFromAccessTokenData.
Is there a way to make this work without having to close and re-open my app?
2)
When I try to get my Friend list using this code:
FBRequest *reqMyFriends = [FBRequest requestForMyFriends];
reqMyFriends.session = FBSession.activeSession;
[reqMyFriends startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary* result,NSError *error) {
if (!error){
NSArray* friends = [result objectForKey:#"data"];
}
}];
I get this error:
error =
{
code = 190;
"error_subcode" = 460;
message = "Error validating access token: Session does not match current stored session. This may be because the user changed the password since the time the session was created or Facebook has changed the session for security reasons.";
type = OAuthException;
};
code = 400;
Why do I get this error?

How to get the list of Facebook friends who have not installed the app?

I'm developing a social networking app. I've integrated Facebook SDK 3.14 in my iOS App. Now, I want to get the list of all my Facebook friends so I can invite those friends who are not using the app and send friend requests to those friends who have already installed the app.
I can get the list of friends who already use my apps using "/me/friends".
[FBRequestConnection startWithGraphPath:#"/me/friends"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSLog(#"All == %#", result);
}];
It gives friends' Facebook ids (ex. id = 654330727444458) in response so that I can send friend requests to them.
To get the list of all Facebook friends who have not downloaded the app and if I want to invite those, I need to get all friends using "me/taggable_friends" (Please correct me if I'm wrong).
[FBRequestConnection startWithGraphPath:#"/me/taggable_friends"
parameters:nil
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSlog("%#", result);
}];
In the taggable_friends response I'm getting friend's id as id = "AaLYBzZzHdzCmlytqyMAjO0OLDZIOs74Urn93ikeRmmTB3vX_Xl81OYUt4XnoWG0BDLuX67umVkheVdDjzyvm0fcqMqu84GgM9JnNHc-1B63eg" which is friend's token id and it's not unique. I couldn't use it instead, have to use Facebook Id of friend to invite them. Unfortunately, I couldn't get it in the taggable friend response.
This is only possible on the Facebook API v1 which stops working next April or so. Even now only existing Facebook apps will allow you to use V1 so if you don't have an old enough app you are not able to do this. In V2 you can only get friends who have also signed in to the same app but the user id's are unique to the application to prevent exactly this. I guess Facebook reasons that by doing this is stops people spamming their friends via apps so much :/
As #joelrb says you can create a canvas app for a game and use invitable_friends but FB will vet your "game" so you can't really cheat.
See https://developers.facebook.com/docs/apps/changelog/ for more info.
TLDR; post to wall is all you can do. Tough. Sorry.
Use the installed field of a user. Like so:
NSMutableArray *notYetUsers = [NSMutableArray array];
FBRequest *fbRequest = [FBRequest requestForGraphPath:#"me/friends?fields=installed"];
[fbRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
NSAssert(!error, error.localizedDescription);
NSArray *friends = [(NSDictionary *)result objectForKey:#"data"];
for (NSDictionary<FBGraphUser> *user in friends) {
if ([user[#"installed"] isEqual:#(NO)])
[notYetUsers addObject:user];
}
}];
notYetUsers would contain all friends who have not installed the app yet.
- (void)getFBFriendsWithCompletion:(void (^)(NSError *, id))callback
{
NSString *query = #"select uid, name, is_app_user "
#"from user "
#"where uid in (select uid2 from friend where uid1=me() )";
NSDictionary *queryParam =
[NSDictionary dictionaryWithObjectsAndKeys:query, #"q", nil];
// Make the API request that uses FQL
[FBRequestConnection startWithGraphPath:#"/fql"
parameters:queryParam
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (callback)
callback(error, result);
}];
}
- (void)foo
{
[self getFBFriendsWithCompletion:^(NSError *error, id result) {
if (!error)
{
NSMutableArray *friendsUsingApp = [NSMutableArray array];
NSMutableArray *friendsNotUsingApp = [NSMutableArray array];
for (NSDictionary *data in result[#"data"]) {
if ([data[#"is_app_user"] boolValue] == NO) {
[friendsNotUsingApp addObject:data];
} else {
[friendsUsingApp addObject:data];
}
}
// Do something with friendsUsingApp and friendsNotUsingApp
}
}];
}
taggable_friends refers to a list of friends that can be tagged or mentioned in stories published to Facebook. The result you got is just a tagging token which can only be used in order to tag a friend, and for no other purpose.
Although this refers to a game app, it's easier I think if you use the invitable_friends API. But it requires a Facebook Canvas app implementation. You may just provide a notice in your Canvas for users to just use the mobile app instead, etc.
This is the tutorial that uses invitable_friends API: https://developers.facebook.com/docs/games/mobile/ios-tutorial/
And, the invitable_friends API details:
https://developers.facebook.com/docs/games/invitable-friends/v2.0
You can try this to get the IDs of Friends app users:
NSMutableArray *appFriendUsers = [[NSMutableArray alloc] init];
[[FBRequest requestForGraphPath:#"me/friends?fields=installed"]
startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary *result,
NSError *error) {
//if result, no errors
if (!error && result)
{
//result dictionary in key "data"
NSArray *allFriendsList = [result objectForKey:#"data"];
if ([allFriendsList count] > 0)
{
// Loop
for (NSDictionary *aFriendData in allFriendsList) {
// Friend installed app?
if ([aFriendData objectForKey:#"installed"]) {
[appFriendUsers addObject: [aFriendData objectForKey:#"id"]];
break;
}
}
}
}
}];

Resources