How to get facebook id of friends - ios

I want to get facebookid of my friends. But seems like its sending different id's
The situation is i have a friends name "abc" when i loads the friends list then i am getting following response for friend "abc" from facebook
<__NSCFArray 0xce76290>(
{
id = 668201987254085;
name = "abc";
}
)
and my facebook id is "123764734754"returned by facebook
i am using below code for this
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
SLRequest *friendsListRequest = [SLRequest requestForServiceType:SLServiceTypeFacebook
requestMethod:SLRequestMethodGET
URL:URLIFY(#"https://graph.facebook.com/me/friends")
parameters:nil];
friendsListRequest.account = facebookAccount;
[friendsListRequest performRequestWithHandler:^(NSData *responseData, NSHTTPURLResponse *urlResponse, NSError *error) {
if (responseData) {
NSLog(#"Got a response: %#", [[NSString alloc] initWithData:responseData
encoding:NSUTF8StringEncoding]);
if (urlResponse.statusCode >= 200 && urlResponse.statusCode < 300) {
NSError *jsonError = nil;
NSDictionary *friendsListData = [NSJSONSerialization JSONObjectWithData:responseData
options:NSJSONReadingAllowFragments
error:&jsonError];
if (jsonError) {
NSLog(#"Error parsing friends list: %#", jsonError);
} else {
self.userList = friendsListData[#"data"];
}
} else {
NSLog(#"HTTP %ld returned", (long)urlResponse.statusCode);
}
} else {
NSLog(#"ERROR Connecting");
}
dispatch_async(dispatch_get_main_queue(), ^{
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
});
}];
But when i am logging in using user name "abc" then for abc (current login user) i am getting different id say "10008772786278"
same thing when i login then i got my facebook id"123764734754" but when my friend "abc" login then in his friends list response they got my id "897349579554"
why this thing happen? how to get same facebook id of the user that is returned after when he login

Please Try this code.
[FBSession openActiveSessionWithReadPermissions:#[#"basic_info"] allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState state, NSError *error){
NSLog(#"Error :%#",error);
if (session.isOpen && !error) {
[FBRequestConnection startWithGraphPath:#"me/friends" parameters:nil HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection,id result, NSError *error){
if (!error) {
NSLog(#"result %#",result);
[array_firendList addObjectsFromArray:[result valueForKey:#"data"]];
NSLog(#"count %ld",(unsigned long)[array_firendList count]);
}
}];

Facebook recently changed a lot of stuff, see here: https://developers.facebook.com/docs/apps/changelog
See "App-scoped User IDs", you don´t get the real IDs anymore:
To better protect people's information, when people log into a version
of your app that has been upgraded to use Graph API v2.0, Facebook
will now issue an app-scoped ID rather than that person's orginal ID
Also important:
The /me/friends endpoint no longer includes the full list of a
person's friends. Instead, it now returns the list of that person's
friends who are also using your app.
To make sure you always get an App Scoped ID, use /v2.0/{object} instead of /{object}. For example, to get the ID of the logged in user you can use /v2.0/me, for getting the friend list you can use /v2.0/me/friends. This is only necessary if your App is created before May 2014, if you created it later it will only use v2.0 anyway.
Another hint: make sure you get the IDs (with /me or /me/friends) on the same platform and of course with the same App, don´t compare the IDs you get with the Graph API Explorer (for example) with the ones you get in the App.

Related

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.

Can't get permissions for user_birthday and user_hometown in facebook-ios-sdk

I am not able to get the permissions for user_birthday and user_hometown.
I tried it with this code before but it only asks for the public profile and ignores others.
[FBSession openActiveSessionWithReadPermissions:#[#"public_profile",#"user_birthday",#"user_hometown"]
allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (error) {
NBAppDelegate* appDel = (NBAppDelegate*)`[UIApplication sharedApplication].delegate;
[appDel sessionStateChanged:session state:status error:error];
}
if ([session isOpen]) {
[self loginWithFBToken:session name:sender];
}
}];
Then someone suggested to ask for additional permissions after getting the public profile, so i even tried that to no good.
Here is the code for that
- (void)loadFbDetails
{
NSArray *permissionsNeeded = #[#"user_hometown", #"user_birthday"];
// Request the permissions the user currently has
[FBRequestConnection startWithGraphPath:#"/me/permissions"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error){
// These are the current permissions the user has:
NSDictionary *currentPermissions= [(NSArray *)[result data] objectAtIndex:0];
// We will store here the missing permissions that we will have to request
NSMutableArray *requestPermissions = [[NSMutableArray alloc] initWithArray:#[]];
// Check if all the permissions we need are present in the user's current permissions
// If they are not present add them to the permissions to be requested
for (NSString *permission in permissionsNeeded){
if (![currentPermissions objectForKey:permission]){
[requestPermissions addObject:permission];
}
}
// If we have permissions to request
if ([requestPermissions count] > 0){
// Ask for the missing permissions
[FBSession.activeSession
requestNewReadPermissions:requestPermissions
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// Permission granted
NSLog(#"new permissions %#", [FBSession.activeSession permissions]);
// We can request the user information
[self makeRequestForUserData];
} else {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
}
}];
} else {
// Permissions are present
// We can request the user information
[self makeRequestForUserData];
}
} else {
// An error occurred, we need to handle the error
// See: https://developers.facebook.com/docs/ios/errors
}
}];
}
-(void)makeRequestForUserData
{
[FBRequestConnection startWithGraphPath:#"me?fields=birthday,hometown"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// Sucess! Include your code to handle the results here
NSLog(#"user events: %#", result);
} else {
NSLog(#"error: %#" , error);
}
}];
}
All it does is recursively go between my ios app and the fb native app, returning only with the public_profile in the permissions array.
Looks like i am missing something?
It should work if you're using an admin user of the app. Once you want to use the extended permissions with other users, you have to get your app reviewed by Facebook first.
See my answer here: facebook extended permission
Facebook does not allow apps to access that information by default. You have to ask permission to Facebook for you to be able to use that information. Add a video and instructions for a Facebook employee review how you're using birthday and hometown intel.

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;
}
}
}
}
}];

How do you get a list of pages a user has created and how do you post to a particular page

I am obviously missing something here. I can successfully login to FB and can access all of the user data. However I see no references on how to work with the users pages that they have created and then allow them to post to the pages.
I am wanting to allow the user to choose which of his pages he wants to post to and then post to them.
So here is what I am dealing with in the code, I am successfully logged on and can post to my wall. Here is the code I am using at that point to get the list of
NSArray *pagePermissionsNeeded = #[#"manage_pages"];
[FBRequestConnection startWithGraphPath:#"/me/accounts"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error){
NSDictionary *currentPermissions= [(NSArray *)[result data] objectAtIndex:0];
NSMutableArray *requestPermissions = [[NSMutableArray alloc] initWithArray:#[]];
for (NSString *permission in pagePermissionsNeeded){
if (![currentPermissions objectForKey:permission]){
[requestPermissions addObject:permission];
}
}
if ([requestPermissions count] > 0){
[FBSession.activeSession requestNewPublishPermissions:requestPermissions
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
[self functiontoListPages];
} else {
NSLog(#"%#", error.description);
}
}];
} else {
[self functiontoListPages];
}
} else {
NSLog(#"%#", error.description);
}
}];
I used the code from th Facebook samples as my starting point and a trying to figure it out. I still have yet to be able to find anything outside of FB to give samples or tutorials.
You need to gather the manage_pages permission in the OAuth process to be able to do this. Then, you can get the Page Access Tokens by requesting
/me/accounts
for the relevant user. See docs at https://developers.facebook.com/docs/facebook-login/permissions#reference-pages

Errors when posting to a friends feed using FB iOS SDK

Some form of this has been asked/answered before but I'm still pretty hazy on the issue. I'm trying to post to a friends feed but keep getting "error com.facebook.sdk code = 5" errors when trying to use startWithGraphPath: from the new FB SDK for ios. The FBSession is active and open and the access_token appears to be correct... Here's some code:
-(void)inviteUser:(NSString *)whoever {
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
// No permissions found in session, so ask for it
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"] defaultAudience:FBSessionDefaultAudienceFriends completionHandler:^(FBSession *session, NSError *error) {
if (!error){
[self sendInvite:whoever];
}
}
}];
}
-(void) sendInvite:(NSString *)whoever {
NSMutableDictionary *params =
[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"A name of something", #"name",
nil];
[FBRequestConnection
startWithGraphPath:[NSString stringWithFormat:#"%#/feed", whoever]
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
NSString *alertText;
if (error) {
alertText = [NSString stringWithFormat:
#"error: domain = %#, code = %d",
error.domain, error.code];
} else {
alertText = #"Posted successfully.";
}
// Show the result in an alert
[[[UIAlertView alloc] initWithTitle:#"Result"
message:alertText
delegate:self
cancelButtonTitle:#"OK!"
otherButtonTitles:nil]
show];
}];
I'm still new at this, and am probably missing something basic. But I'm just not seeing it.
Fixed it. I think there were two problems:
Not having the session properly communicated inside the app (i.e. I had the FBSession open in a loginController, but not in the sendInvite controller <- not the exact names, obviously). As a result, the access_token actually wasn't active. I should have followed the FB docs and put the FBSession methods in the appdelegate.
I was using "publish_action" permissions when I believe I should have been using "publish_stream."
Works smoothly with these two changes. I do have a follow-up question, though: how to post on someone else's wall using the new SDK's native share dialog? I'll probably ask this as a separate question.

Resources