fbsdkloginkit fbsdkcorekit developer ios objective-c facebook cocoa-touch facebook-friends

fbsdkcorekit - Facebook iOS SDK-obtén lista de amigos



facebook sdk version (11)

Usando el SDK de iOS de Facebook, ¿cómo puedo obtener un NSArray de todos mis amigos y enviarles una invitación a mi aplicación? Estoy buscando específicamente la ruta de gráficos para obtener todos los amigos.


// declara una matriz en el archivo de encabezado que contendrá la lista de todos los amigos - NSMutableArray * m_allFriends;

// alloc e inicializa la matriz solo una vez m_allFriends = [[NSMutableArray alloc] init];

Con FB SDK 3.0 y la versión API de arriba 2.0 necesita llamar a la función siguiente (api de gráficos conmigo / amigos) para obtener una lista de amigos de FB que usa la misma aplicación.

// obtener amigos que usan la aplicación

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

Nota: 1) El límite predeterminado para el número de amigos devueltos por la consulta anterior es 25. 2) Si el siguiente enlace aparece como resultado, significa que hay más amigos que irá a buscar en la próxima consulta, y así sucesivamente. 3) Alternativamente, puede cambiar el límite (reducir el límite, superar el límite de 25) y pasarlo en param.

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

Para amigos que no usan aplicaciones:

// m_invitableFriends - array global que contendrá la lista de amigos inviables

Además, para obtener amigos que no sean de la aplicación, debe usar (/ me / invitable_friends) como se indica a continuación:

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


Aquí hay una solución más completa:

En tu archivo de encabezado:

@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

Luego en su implementación:

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

Entonces necesitas al menos el siguiente método de protocolo delegado:

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


Aquí hay una versión 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) } }


Con Facebook SDK 3.2 or above , tenemos una FBWebDialogs clase FBWebDialogs que abre una vista que ya contiene la lista de amigos. Pick the friends y send invitations to all of them . No es necesario usar ninguna llamada API adicional.

Here he descrito brevemente la resolución paso a paso.


Con Facebook SDK 3.0 puedes hacer esto:

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


Para invitar a un amigo que no es una aplicación

Obtendrás tokens de invitación con la lista de amigos devuelta por mi / invitable_friends graph api. Puede usar estos tokens de invitación con FBWebDialogs para enviar invitaciones a amigos como se muestra a continuación.

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



Tal vez esto podría ayudar

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


Use la función siguiente para buscar asincrónicamente amigos del usuario almacenados en un 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); }]; }

En tu código, puedes usarlo como tal:

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


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


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