Facebook iOS SDK - get friends list
Asked Answered
R

11

32

Using the Facebook iOS SDK, how can I get an NSArray of all my friends and send them an invitation to my app? I am specifically looking for the graph path to get all of the friends.

Rhapsodist answered 10/7, 2011 at 3:17 Comment(0)
G
74

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: %lu friends", (unsigned long)friends.count);
    for (NSDictionary<FBGraphUser>* friend in friends) {
        NSLog(@"I have a friend named %@ with id %@", friend.name, friend.objectID);
    }
}];
Gunnar answered 24/9, 2012 at 19:7 Comment(7)
Thanks, your code works perfectly for me. But now i want friend's birthdate also and i tried it by adding one more field in your code(i.e. friend.birthday), but it returns me null value for birthdate only. Here's my code :- for(NSDictionary<FBGraphUser>* friend in friends) { NSLog(@"I have a friend named %@ with id %@, with birthdate=%@", friend.name, friend.id,friend.birthday ); } can you please tell me what should i do to get friend's birthdate also?Antitoxic
Have you asked for friends_birthday permissions?Intermezzo
finally got the solution #13171350Antitoxic
Its returning only the friends who will use the app. But how to get the list of all my friends that are in my FB?Beckerman
This getting data is nil, but friends count is correctDoorstop
in latest facebook friend sdk you can not fetch list of friends directly .Pokeweed
It gives an error : message = "(#100) Unknown fields: username.Sacerdotal
I
14

Here is a more complete solution:

In your header file:

@interface myDelegate : NSObject <UIApplicationDelegate, FBSessionDelegate, FBRequestDelegate> {
    Facebook *facebook;
    UIWindow *window;
    UINavigationController *navigationController;

    NSArray *items; // to get facebook friends
}

@property (nonatomic, retain) IBOutlet UIWindow *window;
@property (nonatomic, retain) IBOutlet UINavigationController *navigationController;

@property (nonatomic, retain) Facebook *facebook;
@property (nonatomic, retain) NSArray *items;
@end

Then in your implementation:

@implementation myDelegate

@synthesize window;
@synthesize navigationController;
@synthesize facebook;
@synthesize items;

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

...


    facebook = [[Facebook alloc] initWithAppId:@"YOUR_APP_ID_FROM_FACEBOOK" andDelegate:self];

    [facebook requestWithGraphPath:@"me/friends" andDelegate:self];

    return YES;
}

Then you need at least the following delegate protocol method:

- (void)request:(FBRequest *)request didLoad:(id)result {
    //ok so it's a dictionary with one element (key="data"), which is an array of dictionaries, each with "name" and "id" keys
    items = [[(NSDictionary *)result objectForKey:@"data"]retain];
    for (int i=0; i<[items count]; i++) {
        NSDictionary *friend = [items objectAtIndex:i];
        long long fbid = [[friend objectForKey:@"id"]longLongValue];
        NSString *name = [friend objectForKey:@"name"];
        NSLog(@"id: %lld - Name: %@", fbid, name);
    }
}
Inkster answered 23/9, 2011 at 14:48 Comment(6)
You're iterating over a dictionary?Nazarite
No, he's iterating over items, which is an NSArray.Villatoro
Can we retrieve email of facebook friends ?Stook
I wouldn't call it more complete, but is a good example of using the delegate style. The new style with blocks is easier, IMHO.Gunnar
How do you use Facebook type? I imported this: #import <FacebookSDK/FacebookSDK.h> but that Facebook data type is unrecognized.Selfseeking
Should I get friends birthday too ?Goose
C
10

To get list of friends you can use

https://graph.facebook.com/me/friends

[facebook requestWithGraphPath:@"me/friends"
                     andParams:nil
                   andDelegate:self];

To know more about all the possible API please read

https://developers.facebook.com/docs/reference/api/

Conviction answered 10/7, 2011 at 7:44 Comment(2)
Getting blank dataGuthrie
@shwetasharma You're probably getting blank data because you don't have friends connected to your app. This only show user friends that already made a connection using Facebook in your appNorthcutt
S
8

Maybe this could help

[FBRequestConnection startForMyFriendsWithCompletionHandler:
 ^(FBRequestConnection *connection, id<FBGraphUser> friends, NSError *error) 
  { 
     if(!error){
       NSLog(@"results = %@", friends);
     }
  }
];
Salzhauer answered 28/2, 2013 at 3:1 Comment(2)
This gives me only count of friends but not their names. Don't know where I am going wrong.Rightly
'FBGraphUser' object have .name and .id properties. Please check those.Salzhauer
D
3

Use the function below to asynchronously fetch user's friends stored in an NSArray:

- (void)fetchFriends:(void(^)(NSArray *friends))callback
{
    [FBRequestConnection startForMyFriendsWithCompletionHandler:^(FBRequestConnection *connection, id response, NSError *error) {
        NSMutableArray *friends = [NSMutableArray new];
        if (!error) {
            [friends addObjectsFromArray:(NSArray*)[response data]];
        }
        callback(friends);
    }];
}

In your code, you can use it as such:

[self fetchFriends:^(NSArray *friends) {
    NSLog(@"%@", friends);
}];
Dumyat answered 27/4, 2014 at 17:0 Comment(0)
E
2

// 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];
}
Exit answered 16/12, 2014 at 6:20 Comment(0)
T
1

With facebook SDK 3.2 or above we have a facility of FBWebDialogs class that opens a view which already contains the friend(s) list. Pick the friends and send invitations to all of them. No need to use any additional API calls.

Here i have briefly described the resolution step-by-step.

Tilth answered 20/5, 2013 at 19:30 Comment(0)
M
1
(void)getFriendsListWithCompleteBlock:(void (^)(NSArray *, NSString *))completed{

if (!FBSession.activeSession.isOpen)
{
    NSLog(@"permissions::%@",FBSession.activeSession.permissions);

    // if the session is closed, then we open it here, and establish a handler for state changes
    [FBSession openActiveSessionWithReadPermissions:@[@"basic_info", @"user_friends"]
                                       allowLoginUI:YES
                                  completionHandler:^(FBSession *session,
                                                      FBSessionState state,
                                                      NSError *error) {
                                      if (error)
                                      {
                                          UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                                              message:error.localizedDescription
                                                                                             delegate:nil
                                                                                    cancelButtonTitle:@"OK"
                                                                                    otherButtonTitles:nil];
                                          [alertView show];
                                      }
                                      else if (session.isOpen)
                                      {
                                          [self showWithStatus:@""];
                                          FBRequest *friendRequest = [FBRequest requestForGraphPath:@"me/friends?fields=name,picture,gender"];


                                              [friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
                                                  NSArray *data = [result objectForKey:@"data"];
                                                  NSMutableArray *friendsList = [[NSMutableArray alloc] init];
                                                  for (FBGraphObject<FBGraphUser> *friend in data)
                                                  {
                                                      //NSLog(@"friend:%@", friend);
                                                      NSDictionary *picture = [friend objectForKey:@"picture"];
                                                      NSDictionary *pictureData = [picture objectForKey:@"data"];
                                                      //NSLog(@"picture:%@", picture);
                                                      FBData *fb = [[FBData alloc]
                                                                    initWithData:(NSString*)[friend objectForKey:@"name"]
                                                                    userID:(NSInteger)[[friend objectForKey:@"id"] integerValue]
                                                                    gender:(NSString*)[friend objectForKey:@"gender"]
                                                                    photoURL:(NSString*)[pictureData objectForKey:@"url"]
                                                                    photo:(UIImage*)nil
                                                                    isPhotoDownloaded:(BOOL)NO];
                                                      [friendsList addObject:fb];
                                                  }

                                                  [self dismissStatus];
                                                  if (completed) {
                                                      completed(friendsList,@"I got it");
                                                  }
                                              }];


                                      }
                                  }];
    }
}
Machismo answered 14/9, 2014 at 4:58 Comment(0)
I
0

Here is a Swift Version.

var friendsRequest : FBRequest = FBRequest.requestForMyFriends()
friendsRequest.startWithCompletionHandler{(connection:FBRequestConnection!, result:AnyObject!, error:NSError!) -> Void in
    let resultdict = result as NSDictionary
    let friends : NSArray = resultdict.objectForKey("data") as NSArray

    println("Found: \(friends.count) friends")
    for friend in friends {
        let id = friend.objectForKey("id") as String
        println("I have a friend named \(friend.name) with id " + id)
    }
}
Intransitive answered 7/11, 2014 at 1:13 Comment(2)
So I printed the incoming resultdict and got following string: { data = (); summary = { "total_count" = 390; }; }. In my case the data is empty, I'm asking for following permissions: "public_profile", "email", "user_friends". Where I should call this functionality? In loginViewFetchedUserInfo?Wiseacre
Please note that since Graph API 2.0, facebook will return only your friends that already gave permission to your facebook app. So, make sure you have some friends that already gave permissions to your facebook app.Intransitive
E
0

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);
                 }
             }
         }
     }];
}
Exit answered 16/12, 2014 at 6:32 Comment(2)
Hello, Is still inviting fb friends is working in latest sdk ?Minard
@Abha, if you are using Facebook SDK version 4.0 for iOS, than you need to show a invite dialog using FBSDKAppInviteDialog (which will display a list of inevitable FB Friends who haven't installed your app). To implement the same, please refer developers.facebook.com/docs/app-invites/iosExit
J
-2
-(void)getFBFriends{

    NSDictionary *queryParam =
    [NSDictionary dictionaryWithObjectsAndKeys:@"SELECT uid, sex,name,hometown_location,birthday, pic_square,pic_big FROM user WHERE uid = me()"
     @"OR uid IN (SELECT uid2 FROM friend WHERE uid1 = me())", @"q", nil];
    // 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 {
                                  NSDictionary *data=result;
                                  //NSLog(@"the returned data of user is %@",data);
                                  NSArray *dataArray=[data objectForKey:@"data"];
                                //dataArray contains first user as self user and your friend list

                              }
                          }];
}
Jeannajeanne answered 3/7, 2014 at 11:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.