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 ge
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);
}];
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.
Maybe this could help
[FBRequestConnection startForMyFriendsWithCompletionHandler:
^(FBRequestConnection *connection, id<FBGraphUser> friends, NSError *error)
{
if(!error){
NSLog(@"results = %@", friends);
}
}
];
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);
}
}
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/