Facebook iOS SDK - 获取好友列表
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6638955/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Facebook iOS SDK - get friends list
提问by user635064
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.
使用 Facebook iOS SDK,如何获取NSArray
我所有朋友中的一个并向他们发送访问我的应用程序的邀请?我特别在寻找获取所有朋友的图形路径。
回答by Jeff
With Facebook SDK 3.0 you can do this:
使用 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);
}
}];
回答by JeffB6688
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);
}
}
回答by imthi
To get list of friends you can use
要获取您可以使用的朋友列表
https://graph.facebook.com/me/friends
https://graph.facebook.com/me/friends
[facebook requestWithGraphPath:@"me/friends"
andParams:nil
andDelegate:self];
To know more about all the possible API please read
要了解有关所有可能的 API 的更多信息,请阅读
回答by John Paul Manoza
Maybe this could help
也许这会有所帮助
[FBRequestConnection startForMyFriendsWithCompletionHandler:
^(FBRequestConnection *connection, id<FBGraphUser> friends, NSError *error)
{
if(!error){
NSLog(@"results = %@", friends);
}
}
];
回答by Zorayr
Use the function below to asynchronously fetch user's friends stored in an NSArray:
使用下面的函数异步获取存储在 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);
}];
回答by Sanjay Mohnani
// declare an array in header file which will hold the list of all friends - NSMutableArray * m_allFriends;
// 在头文件中声明一个数组,该数组将保存所有朋友的列表 - NSMutableArray * m_allFriends;
// alloc and initialize the array only once m_allFriends = [[NSMutableArray alloc] init];
// 只分配和初始化数组一次 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.
使用 FB SDK 3.0 和高于 2.0 的 API 版本,您需要调用以下函数(与我/朋友一起绘制图形 api)以获取使用相同应用程序的 FB 朋友列表。
// 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.
注意:1)上述查询返回的好友数量的默认限制是25。2)如果下一个链接出现在结果中,这意味着您将在下一次查询中获取更多好友,依此类推。3)或者,您可以更改限制(减少限制,超过 25 的限制)并在参数中传递它。
////////////////////////////////////////////////////////////////////////
////////////////////////////////////////////////// //////////////////////
For non app friends -
对于非应用程序的朋友 -
// m_invitableFriends - global array which will hold the list of invitable friends
// m_invitableFriends - 保存可邀请好友列表的全局数组
Also to get non app friends you need to use (/me/invitable_friends) as below -
同样要获得非应用好友,您需要使用 (/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];
}
回答by Minh Ti?n
(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");
}
}];
}
}];
}
}
回答by NeverHopeless
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.
使用 facebook,SDK 3.2 or above
我们有一个FBWebDialogs
类的设施,可以打开一个已经包含朋友列表的视图。Pick the friends
和send invitations to all of them
。无需使用任何额外的 API 调用。
Herei have briefly described the resolution step-by-step.
在这里,我已经简要描述了逐步解决方案。
回答by lucaslt89
Here is a Swift Version.
这是一个 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)
}
}
回答by Sanjay Mohnani
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
您将获得带有 me/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);
}
}
}
}];
}