【问题标题】:Facebook iOS SDK - get friends listFacebook iOS SDK - 获取好友列表
【发布时间】:2026-01-26 15:05:01
【问题描述】:

使用 Facebook iOS SDK,我如何获得我所有朋友的 NSArray 并向他们发送我的应用程序的邀请?我是专门找图路径来获取所有朋友的。

【问题讨论】:

    标签: ios objective-c facebook cocoa-touch facebook-friends


    【解决方案1】:

    获取您可以使用的朋友列表

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

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

    要了解有关所有可能的 API 的更多信息,请阅读

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

    【讨论】:

    • 获取空白数据
    • @shwetasharma 您可能会收到空白数据,因为您没有朋友连接到您的应用程序。这仅显示已在您的应用中使用 Facebook 建立联系的用户朋友
    【解决方案2】:

    这里有一个更完整的解决方案:

    在你的头文件中:

    @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
    

    然后在你的实现中:

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

    那么你至少需要以下委托协议方法:

    - (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);
        }
    }
    

    【讨论】:

    • 您正在遍历字典?
    • 不,他在迭代项目,这是一个 NSArray。
    • 我们可以找回facebook好友的email吗?
    • 我不会说它更完整,但它是使用委托样式的一个很好的例子。恕我直言,带有块的新样式更容易。
    • 你是如何使用 Facebook 类型的?我导入了这个:#import 但 Facebook 数据类型无法识别。
    【解决方案3】:

    使用 Facebook SDK 3.0,您可以做到这一点:

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

    【讨论】:

    • 你申请了friends_birthday权限吗?
    • 终于得到了解决方案*.com/questions/13170850/…
    • 它只返回将使用该应用程序的朋友。但是如何获取我在我的 FB 中的所有朋友的列表?
    • 本次获取数据为nil,但好友数正确
    • 在最新的facebook好友sdk中你不能直接获取好友列表。
    【解决方案4】:

    也许这会有所帮助

    [FBRequestConnection startForMyFriendsWithCompletionHandler:
     ^(FBRequestConnection *connection, id<FBGraphUser> friends, NSError *error) 
      { 
         if(!error){
           NSLog(@"results = %@", friends);
         }
      }
    ];
    

    【讨论】:

    • 这只给了我朋友的数量,而不是他们的名字。不知道我哪里错了。
    • 'FBGraphUser' 对象具有 .name 和 .id 属性。请检查这些。
    【解决方案5】:

    使用 facebook SDK 3.2 or above 我们有一个 FBWebDialogs 类的工具,可以打开一个已经包含朋友列表的视图。 Pick the friendssend invitations to all of them无需使用任何额外的 API 调用。

    Here我已经简单描述了一步一步的解决方法。

    【讨论】:

      【解决方案6】:

      使用以下函数异步获取存储在 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);
          }];
      }
      

      在您的代码中,您可以这样使用它:

      [self fetchFriends:^(NSArray *friends) {
          NSLog(@"%@", friends);
      }];
      

      【讨论】:

        【解决方案7】:
        -(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
        
                                      }
                                  }];
        }
        

        【讨论】:

          【解决方案8】:
          (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");
                                                            }
                                                        }];
          
          
                                                }
                                            }];
              }
          }
          

          【讨论】:

            【解决方案9】:

            这是一个 Swift 版本。

            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)
                }
            }
            

            【讨论】:

            • 所以我打印了传入的resultdict 并得到以下字符串:{ data = (); summary = { "total_count" = 390; }; }。在我的情况下,数据为空,我要求以下权限:"public_profile", "email", "user_friends"。我应该在哪里调用此功能?在loginViewFetchedUserInfo?
            • 请注意,自 Graph API 2.0 起,facebook 将仅返回已授予您 Facebook 应用程序权限的朋友。因此,请确保您有一些朋友已经授予了您的 Facebook 应用程序的权限。
            • 是的,我想通了。谢谢你的回答!
            【解决方案10】:

            // 在头文件中声明一个数组,该数组将保存所有朋友的列表 - NSMutableArray * m_allFriends;

            // 只分配和初始化数组一次 m_allFriends = [[NSMutableArray alloc] init];

            使用 FB SDK 3.0 和 2.0 以上的 API 版本,您需要调用以下函数(与我/朋友的图形 api)来获取使用相同应用程序的 FB 朋友列表。

            // 获取使用该应用的朋友

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

            注意:1)上述查询返回的好友数量默认限制为25。 2)如果下一个链接出现在结果中,这意味着您将在下一个查询中获取更多朋友,依此类推。 3)或者,您可以更改限制(减少限制,超过 25 的限制)并在参数中传递。

            /////////////////////////////////////// //////////////////////

            对于非应用好友 -

            // m_invitableFriends - 保存邀请好友列表的全局数组

            还要获得非应用好友,您需要使用 (/me/invitable_friends) 如下 -

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

            【讨论】:

              【解决方案11】:

              用于邀请非应用好友 -

              您将获得带有我/invitable_friends graph api返回的朋友列表的邀请令牌。您可以将这些邀请令牌与 FBWebDialogs 一起使用,如下所示向朋友发送邀请

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

              【讨论】:

              • 你好,还在用最新的sdk邀请fb好友吗?
              • @Abha,如果您使用适用于 iOS 的 Facebook SDK 4.0 版,则需要使用 FBSDKAppInviteDialog 显示邀请对话框(这将显示未安装您应用的不可避免的 FB 好友列表) .要实现相同,请参考developers.facebook.com/docs/app-invites/ios