2011-07-10 189 views

回答

10

要獲取好友列表,你可以使用

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

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

爲了更多地瞭解所有可能的API,請閱讀

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

+0

獲取空白數據 –

+1

@shwetasharma你可能會得到空數據,因爲你沒有朋友連接到您的應用程序。這隻顯示已經在您的應用中使用Facebook進行連接的用戶朋友 – dulgan

14

下面是一個更完整的解決方案:

在你的頭文件:

@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); 
    } 
} 
+0

您正在迭代字典? – Tudorizer

+1

不,他正在迭代NSArray的項目。 –

+1

我們可以檢索Facebook好友的電子郵件嗎? – booker

74

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

謝謝,你的代碼完全適合我。但是現在我想要朋友的出生日期,我試着在代碼中添加一個字段(即friend.birthday),但是它僅返回出生日期的空值。這裏是我的代碼: - 爲(NSDictionary的 *朋友的朋友){ 的NSLog(@ 「我有ID%@個朋友叫%@,用出生日期=%@」,friend.name,friend.id,friend.birthday ); }你能告訴我我該怎麼做朋友的生日嗎? – stack

+2

你是否要求friends_birthday權限? –

+2

終於得到了解決http://stackoverflow.com/questions/13170850/ios-facebook-sdk-3-1-retrieve-friend-birthday-returning-null – stack

8

也許這可以幫助

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

這讓我只算的朋友,但不是他們的名字不知道我要去的地方錯了 –

+0

‘FBGraphUser’對象已。 。名和屬性.ID請檢查那些 –

1

與Facebook SDK 3.2 or above我們FBWebDialogs類的設施,打開裏面已經包含了朋友(s)列表的視圖。 Pick the friendssend invitations to all of them無需使用任何其他API調用。

Here我有簡要描述的分辨率步一步。

3

使用下面的函數異步讀取存儲在一個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); 
}]; 
-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 

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


             } 
            }]; 
    } 
} 
0

這裏是一個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) 
    } 
} 
+0

所以我印刷傳入'''resultdict'''並得到以下字符串:'''{數據=();摘要= { 「TOTAL_COUNT」= 390;};}' ''。在我的情況下,數據是空的,我要求以下權限:''''public_profile「,」email「,」user_friends「'''我應該在哪裏調用這個功能?'''loginViewFetchedUserInfo' ''? –

+0

請注意,自Graph API 2.0以來,facebook只會返回已經授予您的Facebook應用程序許可的朋友。所以,確保你有一些朋友已經給你的Facebook應用程序授予了權限。 – lucaslt89

+0

是的我想通了。謝謝你的答案! –

2

//聲明在頭文件中的數組,其將持有的所有朋友名單 - 的NSMutableArray * m_allFriends;

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

隨着FB SDK 3.0及以上版本,你需要下面的函數調用API 2.0版本(圖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的限制),並將其傳遞給param。

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

對於非應用程序的朋友 -

// m_invitableFriends - 全球陣列將舉行列表的invitable朋友

也得到你需要使用(/ 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]; 
} 
+0

謝謝,它的工作原理! – ondermerol

+0

@ondermerol歡迎 –

0

邀請非應用程序的朋友 -

你會被邀請與由我返回/ invitable_friends圖形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); 
       } 
      } 
     } 
    }]; 
} 
+0

你好,還在邀請fb朋友在最新sdk工作嗎? – Abha

+1

@Abha,如果您使用Facebook SDK版本4.0 for iOS,則需要使用FBSDKAppInviteDialog顯示邀請對話框(其中將顯示未安裝應用的不可避免的FB Friends列表)。要實現相同,請參閱https://developers.facebook.com/docs/app-invites/ios –

+0

非常感謝你... – Abha