I am quite new to objective-C and iPhone Development environment.
I am implementing Facebook login in my app to get User's name, Email and profile Picture. I have successfully implemented login Part and have received name and User ID of the person.
Now i want to get User's Email and Profile Picture from Facebook.But i am not having any Idea how to get it.I am using Facebook IOS SDK v4.0.
How can i fetch User's Profile picture and Email Id from Facebook when i am having User ID?
To get user Email ID you must ask permission for email while logging.
FBSDKLoginButton *loginView = [[FBSDKLoginButton alloc] init];
loginView.readPermissions = #[#"email"];
loginView.frame = CGRectMake(100, 150, 100, 40);
[self.view addSubview:loginView];
You can get user email Id in New SDK using GraphPath.
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%# and Email : %#", result,result[#"email"]);
}
}];
}
result would get you all the user Details and result[#"email"] would get you the email for logged in user.
To get Profile picture you can use
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=normal",result[#"id"]]];
NSData *data = [NSData dataWithContentsOfURL:url];
_imageView.image = [UIImage imageWithData:data];
or u can also use FBSDKProfilePictureView to get profile Picture by passing user profile Id:
FBSDKProfilePictureView *profilePictureview = [[FBSDKProfilePictureView alloc]initWithFrame:_imageView.frame];
[profilePictureview setProfileID:result[#"id"]];
[self.view addSubview:profilePictureview];
Refer to :https://developers.facebook.com/docs/facebook-login/ios/v2.3#profile_picture_view
or u can also get both by passing as parameters
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me"
parameters:#{#"fields": #"picture, email"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString *pictureURL = [NSString stringWithFormat:#"%#",[result objectForKey:#"picture"]];
NSLog(#"email is %#", [result objectForKey:#"email"]);
NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:pictureURL]];
_imageView.image = [UIImage imageWithData:data];
}
else{
NSLog(#"%#", [error localizedDescription]);
}
}];
Sorry for this messy answer, this is my first answer ever. You can use FBSDK Graph request to fetch user's all profile infos and FBSDKProfilePictureView class to fetch user's Profile Picture easily.This code is for manually Facebook login UI.
Firstly, you must put this code where login process start:
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"public_profile", #"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error)
{
// There is an error here.
}
else
{
if(result.token) // This means if There is current access token.
{
// Token created successfully and you are ready to get profile info
[self getFacebookProfileInfo];
}
}
}];
And If login is successfull, implement this method to get user's public profile;
-(void)getFacebookProfileInfos {
FBSDKGraphRequest *requestMe = [[FBSDKGraphRequest alloc]initWithGraphPath:#"me" parameters:nil];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
[connection addRequest:requestMe completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(result)
{
if ([result objectForKey:#"email"]) {
NSLog(#"Email: %#",[result objectForKey:#"email"]);
}
if ([result objectForKey:#"first_name"]) {
NSLog(#"First Name : %#",[result objectForKey:#"first_name"]);
}
if ([result objectForKey:#"id"]) {
NSLog(#"User id : %#",[result objectForKey:#"id"]);
}
}
}];
[connection start];
Get current logged in user's profile picture:
FBSDKProfilePictureView *pictureView=[[FBSDKProfilePictureView alloc]init];
[pictureView setProfileID:#"user_id"];
[pictureView setPictureMode:FBSDKProfilePictureModeSquare];
[self.view addSubview:pictureView];
You must add refreshing code to your viewDidLoad method:
[FBSDKProfile enableUpdatesOnAccessTokenChange:YES];
Hope This could Help You ..
- (IBAction)Loginwithfacebookaction:(id)sender
{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logOut];
[login logInWithReadPermissions:#[#"public_profile"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error)
{
NSLog(#"Process error");
}
else if (result.isCancelled)
{
NSLog(#"Cancelled");
}
else
{
[self getFacebookProfileInfos];
}
}];
}
- (void)finishedWithAuth: (GTMOAuth2Authentication *)auth
error: (NSError *) error {
NSLog(#"Received error %# and auth object %#",error, auth);
if (!error)
{
email =signIn.userEmail;
[[NSUserDefaults standardUserDefaults] setObject:email forKey:#"useremail"];
NSLog(#"Received error and auth object %#",signIn.userEmail);
NSLog(#"Received error and auth object %#",signIn.userID);
if ( auth.userEmail)
{
[[[GPPSignIn sharedInstance] plusService] executeQuery:[GTLQueryPlus queryForPeopleGetWithUserId:#"me"] completionHandler:^(GTLServiceTicket *ticket, GTLPlusPerson *person, NSError *error)
{
// this is for fetch profile image
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:#"%#",person.image.url]];
NSLog(#"%#",url);
name= person.displayName;
[[NSUserDefaults standardUserDefaults] setObject:name forKey:#"userNameLogin"];
[[NSUserDefaults standardUserDefaults] synchronize];
NSLog(#"Name:%#",person.displayName);
[self callWebserviceToUploadImage];
}];
}
}
}
-(void)getFacebookProfileInfos {
FBSDKGraphRequest *requestMe = [[FBSDKGraphRequest alloc]initWithGraphPath:#"/me?fields=first_name, last_name, picture, email" parameters:nil];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
[connection addRequest:requestMe completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(result)
{
if ([result objectForKey:#"email"]) {
email = [result objectForKey:#"email"];
[[NSUserDefaults standardUserDefaults] setObject:email forKey:#"useremail"];
}
if ([result objectForKey:#"first_name"]) {
NSLog(#"First Name : %#",[result objectForKey:#"first_name"]);
name = [result objectForKey:#"first_name"];
[[NSUserDefaults standardUserDefaults] setObject:name forKey:#"userNameLogin"];
}
if ([result objectForKey:#"id"])
{
NSLog(#"User id : %#",[result objectForKey:#"id"]);
}
}
[self callfbloginwebservice];
}];
[connection start];
}
#import <FBSDKCoreKit/FBSDKAccessToken.h>
#import <FBSDKCoreKit/FBSDKGraphRequest.h>
Add YourViewController.h
- (IBAction)loginAction:(id)sender {
// https://developers.facebook.com/docs/graph-api/reference/user
// https://developers.facebook.com/docs/ios/graph
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"email,name,first_name,last_name"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%#", result);
// Here u can update u r UI like email name TextField
}
}];
}
}
Related
I'm trying to get the profile image for a Facebook user using the Graph API in the Facebook SDK for iOS but the example code from the website does not work for me.
https://developers.facebook.com/docs/graph-api/reference/user/picture/
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/123456789/picture"
parameters:nil
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
// Insert your code here
}];
I get the following error in the console.
FBSDKLog: starting with Graph API v2.4, GET requests for //123456789/picture should contain an explicit "fields" parameter
From my understanding of the error message instead of parameters:nil I need to enter something like parameters:#{#"fields": #"id"} but whatever I try result in the completing handler is always nil. I don't know what to enter for the profile picture.
EDIT:
I'm looking to get the profile picture for other users.
Try This One:-
- (IBAction)btnFaceBook:(id)sender {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login setLoginBehavior:FBSDKLoginBehaviorBrowser];
[login logInWithReadPermissions:#[#"public_profile",#"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error)
{
[[FBSDKLoginManager new]logOut];
} else if (result.isCancelled)
{
// Handle cancellations
}
else
{
if ([result.grantedPermissions containsObject:#"email"])
{
[self getDataFromFB];
}
}
}];
}
-(void)getDataFromFB
{
MBProgressHUD *hud=[MBProgressHUD showHUDAddedTo:self.view animated:true];
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"political,picture.width(500).height(500),id,email,first_name,last_name,gender,name" forKey:#"fields"]]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
if (!error && [result count] != 0)
{
[hud hideAnimated:true];
NSLog(#"%#", result);
}
else
{
[hud hideAnimated:true];
[self displayAlertMesage:#"Some error has been occure." title:#"Oops!"];
}
}];
}
}
You can use the following code for getting the data from the facebook login:-
-(void)getFacebookProfileInfos
{
FBSDKGraphRequest *requestMe = [[FBSDKGraphRequest alloc]initWithGraphPath:#"me" parameters:#{#"fields": #"id,email,name,birthday,first_name,last_name,gender,picture.type(large)"}];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
[connection addRequest:requestMe completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(result)
{
dictUserData = [[NSDictionary alloc]init];
dictUserData=result;
}
}];
[connection start];
}
you will get all the data in the "dictUserData" dictionary and from that you will access the facebook profile in this way:-
UIImage * imgProfile = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString stringWithFormat:#"%#", dictUserData[#"picture"][#"data"][#"url"]]]]];
NSString * strImageData = [self imageToNSString:imgProfile];
how to get userprofile in ios
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions: #[#"public_profile",#"email"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(#"Process error");
} else if (result.isCancelled)
{
NSLog(#"Cancelled");
} else {
/*"birthday" will also be fethched*/
/*https://developers.facebook.com/docs/android/graph*/
NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
[parameters setValue:#"id,name,email,gender,first_name,last_name" forKey:#"fields"];
if ([FBSDKAccessToken currentAccessToken])
{
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:parameters]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
if (!error)
{
NSLog(#"fetched user:%#", result);
fbid = [result valueForKey:#"id"];
fbName = [result valueForKey:#"name"];
fbEmail = [result valueForKey:#"email"];
fbGender = [result valueForKey:#"gender"];
fbFirstname = [result valueForKey:#"first_name"];
fbLastname = [result valueForKey:#"last_name"];
// [self fbLoginServerRequest];/********/
}
}
I am not sure why your code is not working. The code below is working for me after I subscribe to the FBSDKLoginButtonDelegate, and the user goes through the all shebang of granting permissions. If you are already signed in, all you need is the GraphPad request. This is assuming that the token is still valid. I would start checking the token validity using the Access Token Tool
- (void)loginButton:(FBSDKLoginButton*)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult*)result
if(error) {
NSLog(#"FB login error %#",error);
} else if(result.isCancelled) {
NSLog(#"FB login cancelled");
} else {
// Check if the user declined permissions
if([result.declinedPermissions count] > 0) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"picture, email, first_name, last_name"}] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
NSLog(#"FBSDKGraphRequest ERROR %#", error);
if (!error) {
NSLog(#"fetched user: %#", result);
NSURL *profileImageURL = [NSURL URLWithString:[NSString stringWithFormat:#"https://graph.facebook.com/me/picture?type=normal&return_ssl_resources=1&access_token=%#",accessToken]];
NSData *imageData = [NSData dataWithContentsOfURL:profileImageURL];
UIImage *image = [UIImage imageWithData:imageData];
NSMutableDictionary *faceBookParametersDictionary = [[NSMutableDictionary alloc] init];
[faceBookParametersDictionary setValue:image forKey:#"image"];
[faceBookParametersDictionary setValue:userID forKey:#"id"];
[faceBookParametersDictionary setValue:result[#"email"] forKey:#"email"];
[faceBookParametersDictionary setValue:result[#"first_name"] forKey:#"firstname"];
[faceBookParametersDictionary setValue:result[#"last_name"] forKey:#"lastname"];
[faceBookParametersDictionary setValue:accessToken forKey:#"token"];
NSLog(#"faceBookParametersDictionary %#", faceBookParametersDictionary);
}
}];
}
}
}
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"public_profile", #"email", #"user_friends"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
// Process error
} else if (result.isCancelled) {
// Handle cancellations
} else {
// Successfull login
if ([result.grantedPermissions containsObject:#"email"]) {
if ([FBSDKAccessToken currentAccessToken]) {
NSLog(#"YES");
NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
[parameters setValue:#"id,name,email,gender,picture" forKey:#"fields"];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:parameters]startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (error) {
// NSLog(#"%#",result);
viwLoginWave.hidden = YES;
[btnLogin setTitle:#"LOGIN" forState:UIControlStateNormal];
self.view.userInteractionEnabled = YES;
}
NSString *email1 = [result objectForKey:#"email"];
if (email1 == nil) {
[appDelegate showProgressWithMessage:#"Unable to access private account."];
}
else {
NSLog(#"You got your stuff.");
NSLog(#"%#",result);
}
}];
}
else {
NSLog(#"NO");
}
}
}
}];
In this printed result, You will get everything you want.
Other required things:
Add following keys in info plist and save your app values.
- Set value for FacebookAppID.
- Set value for FacebookDisplayName
- List item
#interface ViewController ()
{
NSString *getFbid;
NSString *getFbFirstName,*getFBlastName, *getFbemail,*getfbBirthday,*getfbGender,*getFBpHone,*getFBlocation,*getFBcountry;
}
-(void)loginButtonClicked
{
NSUserDefaults *defFacebookData = [NSUserDefaults standardUserDefaults];
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: #[#"public_profile", #"user_friends", #"email"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
DLog(#"Process error======%#",error.description);
indicators.hidden=YES;
[indicators stopAnimating];
} else if (result.isCancelled) {
DLog(#"Cancelled");
indicators.hidden=YES;
[indicators stopAnimating];
} else {
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"id, name, link, first_name, last_name, picture.type(large), email, birthday, bio ,location ,friends ,hometown , gender ,friendlists"}]
startWithCompletionHandler:^(
FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error)
{
// NSLog(#"fetched user:%#", result);
// [self fetchingFacebookFriends];
[defFacebookData setObject:[result objectForKey:#"email"] forKey:#"fbEmail"];
[defFacebookData setObject:[result objectForKey:#"id"] forKey:#"fbID"];
//PASS ID
getFbid = [result objectForKey:#"id"];
NSLog(#"getFbid========>%#",getFbid);
//PASS FIRST NAME
getFbFirstName=[result objectForKey:#"first_name"];
NSLog(#"first======>%#",getFbFirstName);
//PASS LAST NAME
getFBlastName=[result objectForKey:#"last_name"];
NSLog(#"first======>%#",getFBlastName);
//PASS EMAIL
getFbemail=[result objectForKey:#"email"];
NSLog(#"first======>%#",getFbemail);
//PASS PHONE
getfbGender=[result objectForKey:#"gender"];
NSLog(#"first======>%#",getfbGender);
[defFacebookData setObject:[result objectForKey:#"name"] forKey:#"fbName"];
// Image
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:#"me/picture?type=large&redirect=false"]
parameters:nil
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id fbImageResult,
NSError *error) {
NSString *strURL = [NSString stringWithFormat:#"%#",[[fbImageResult objectForKey:#"data"] objectForKey:#"url"]];
NSLog(#"strURL=====>%#",strURL);
[defFacebookData setObject:strURL forKey:#"fbImage"];
[defFacebookData synchronize];
NSDictionary *fbdict=[NSDictionary dictionaryWithObjectsAndKeys:getFbid,#"id",getFbFirstName,#"first_name",getFBlastName,#"last_name",getFbemail,#"email",getfbGender,#"gender",strURL,#"fbImage", nil];
NSLog(#"done=========>%#",fbdict);
}];
}
else{
DLog(#"error is %#", error.description);
}
}];
}
}
}];
}
When user open Facebook Setting View, how to identify the current log in status. And if it is logged, how can i retrieve the users' further information. such as birthday, age, gender, etc.
i wrote this piece of code, which is not working. Thanks in advance.
- (void)viewDidLoad {
[super viewDidLoad];
if ([FBSDKAccessToken currentAccessToken]) {
//Going to another ViewController, which include user's name,
//age, photo and so on.
} else {
FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
loginButton.center = self.view.center;
[self.view addSubview:loginButton];
}
}
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#”fetched user:%#”, result);
}
}];
}
Try this its working .
https://developers.facebook.com/docs/ios/change-log-4.x here is document to get information about SDK 4.0
Here are Some graph api key.
"public_profile",
"email",
"user_friends" ,
"user_hometown",
"user_work_history" ,
"user_birthday" ,
"user_education_history
Here is the full and complete code to fetch user's information
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: #[#"public_profile", #"user_friends", #"email"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
DLog(#"Process error======%#",error.description);
indicators.hidden=YES;
[indicators stopAnimating];
} else if (result.isCancelled) {
DLog(#"Cancelled");
indicators.hidden=YES;
[indicators stopAnimating];
} else {
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"id, name, link, first_name, last_name, picture.type(large), email, birthday, bio ,location ,friends ,hometown , gender ,friendlists"}]
startWithCompletionHandler:^(
FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error)
{
// NSLog(#"fetched user:%#", result);
// [self fetchingFacebookFriends];
[defFacebookData setObject:[result objectForKey:#"email"] forKey:#"fbEmail"];
[defFacebookData setObject:[result objectForKey:#"id"] forKey:#"fbID"];
//PASS ID
getFbid = [result objectForKey:#"id"];
NSLog(#"getFbid========>%#",getFbid);
//PASS FIRST NAME
getFbFirstName=[result objectForKey:#"first_name"];
NSLog(#"first======>%#",getFbFirstName);
//PASS LAST NAME
getFBlastName=[result objectForKey:#"last_name"];
NSLog(#"first======>%#",getFBlastName);
//PASS EMAIL
getFbemail=[result objectForKey:#"email"];
NSLog(#"first======>%#",getFbemail);
//PASS PHONE
getfbGender=[result objectForKey:#"gender"];
NSLog(#"first======>%#",getfbGender);
[defFacebookData setObject:[result objectForKey:#"name"] forKey:#"fbName"];
// Image
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:#"me/picture?type=large&redirect=false"]
parameters:nil
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id fbImageResult,
NSError *error) {
NSString *strURL = [NSString stringWithFormat:#"%#",[[fbImageResult objectForKey:#"data"] objectForKey:#"url"]];
NSLog(#"strURL=====>%#",strURL);
[defFacebookData setObject:strURL forKey:#"fbImage"];
[defFacebookData synchronize];
NSDictionary *fbdict=[NSDictionary dictionaryWithObjectsAndKeys:getFbid,#"id",getFbFirstName,#"first_name",getFBlastName,#"last_name",getFbemail,#"email",getfbGender,#"gender",strURL,#"fbImage", nil];
NSLog(#"done=========>%#",fbdict);
UIStoryboard*storyboard=[AppDelegate storyBoardType];
NSUserDefaults *defaults =[NSUserDefaults standardUserDefaults];
BOOL fblogin =[defaults boolForKey:#"KeyEditProfile"];
if (fblogin)
{
UIStoryboard*Storyboard=[AppDelegate storyBoardType];
DashboardVC* tabbarController = (DashboardVC*)[Storyboard instantiateViewControllerWithIdentifier:#"DashboardVCId"];
indicators.hidden=YES;
[indicators stopAnimating];
[self.navigationController pushViewController:tabbarController animated:YES];
}
else
{
EditFBVC *cpvc=(EditFBVC*)[storyboard instantiateViewControllerWithIdentifier:#"EditFBVCId"];
NSLog(#"get fb id ===%#",getFbid);
cpvc.dictFacebookdict =fbdict;
cpvc.strFBlogin =#"fbAllDataValue";
indicators.hidden=YES;
[indicators stopAnimating];
[self.navigationController pushViewController:cpvc animated:YES];
}
}];
}
else{
DLog(#"error is %#", error.description);
}
}];
}
}
}];
I am trying to get Facebook friend list with name, id, etc in my app.
- (IBAction)onFBLogin:(id)sender {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: #[#"public_profile", #"email", #"user_friends"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(#"Process error");
} else if (result.isCancelled) {
NSLog(#"Cancelled");
} else {
NSLog(#"%#", result);
[self getFBEmailAddress];
}
}];
}
-(void)getFBEmailAddress{
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me"
parameters:#{#"fields": #"picture, email, friends"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString *pictureURL = [NSString stringWithFormat:#"%#",[result objectForKey:#"picture"]];
mFBId = [NSString stringWithFormat:#"%#",[result objectForKey:#"id"]];
NSLog(#"My Profile : %#", result);
NSLog(#"email is %#", [result objectForKey:#"email"]);
[self getFBFriendList];
}
else{
NSLog(#"%#", [error localizedDescription]);
}
}];
}
-(void)getFBFriendList{
NSString* graphPat = [[NSString alloc] initWithFormat:#"%#/friends", mFBId];
FBSDKGraphRequest *requestFriends = [[FBSDKGraphRequest alloc]
initWithGraphPath:graphPat
parameters:#{#"fields": #"id, name"}
HTTPMethod:#"GET"];
[requestFriends startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if (!error && result)
{
NSArray *allFriendsResultData = [result objectForKey:#"data"];
if ([allFriendsResultData count] > 0)
{
for (NSDictionary *friendObject in allFriendsResultData)
{
NSString *friendName = [friendObject objectForKey:#"name"];
NSString *friendID = [friendObject objectForKey:#"id"];
NSLog(#"%# : %#", friendID, friendName);
}
}
}
}];}
I've succeed to login via Facebook and get my profile. After that, I've tried to get friend list via the friends graph api. But at that time, it only said count of friends following as below.
friends = {
data = (
);
summary = {
"total_count" = 2;
};
};
id = 60XXXXXX1295X;
picture = {
data = {
"is_silhouette" = 0;
url = "https://scontent.xx.fbcdn.net/hprofile-xfa1/v/t1.0-1/p50x50/1..._501957533...";
};
};
How Can I get full information of friends list such as id, name, etc? Please help me if any one already implemented. Thank you.
This work for me.
NSMutableArray *completeList = [[NSMutableArray alloc] init];
[self fetchFacebookEachFriend:completeList withGrapPath:#"/me/friends" withCallback:^(BOOL success, NSMutableArray * fbList) {
//Finish get All Friends
fbListFinal(success, fbList);
}];
- (void)fetchFacebookEachFriend:(NSMutableArray *)completeList withGrapPath:(NSString *)graphPath withCallback:(returnFbList)fbList
{
NSDictionary *limitDictionary = [NSDictionary dictionaryWithObjectsAndKeys:#"first_name, last_name, middle_name, name, email", #"fields", nil];
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:graphPath parameters:limitDictionary HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (error) {
[[[UIAlertView alloc] initWithTitle:#"Alert!" message:#"Please connect to Facebook to find your friends" delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil] show];
fbList(NO, completeList);
return;
}
//Add each friend to list
for (NSDictionary *friend in [result valueForKey:#"data"]) {
[completeList addObject:friend];
}
if ([result valueForKey:#"paging"] != nil && [[result valueForKey:#"paging"] valueForKey:#"next"] != nil) {
NSString *nextPage = [[result valueForKey:#"paging"] valueForKey:#"next"];
nextPage = [[nextPage componentsSeparatedByString:#"?"] objectAtIndex:1];
[self fetchFacebookEachFriend:completeList withGrapPath:[NSString stringWithFormat:#"me/friends?%#",nextPage] withCallback:fbList];
} else
fbList(YES, completeList);
}];
}
result.paging.next contains the complete URL, with access token and all. I find the simplest thing is just to pass it on to an NSURLSession data task:
NSString *nextPage = result[#"paging"][#"next"];
if (!nextPage) return;
[[[NSURLSession sharedSession] dataTaskWithURL:[NSURL URLWithString:nextPage] completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
id json = [self decodeJSONResult:data response:response error:error];
// use json
}] resume];
I wrote this as an FBSDKGraphRequest extension: FBSDKGraphRequest+Paging.h
I am trying getting info from Facebook API. The parameters are group in couple catalogs. To get data I using these code below from Facebook SDK:
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"me"
parameters:#{ #"fields" : #"name, birthday"}
HTTPMethod:#"GET"];[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
];
Name of catalog where are data 'name' and 'birthday' is "fields". But I want to get more data from other catalogs (edges, parameters), like first name, last name, email, id, about, etc. How can I write code to get it all?
Put this code
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
// Process error
NSLog(#"error is :%#",error);
}
else if (result.isCancelled)
{
// Handle cancellations
NSLog(#"error is :%#",error);
}
else
{
if ([result.grantedPermissions containsObject:#"email"])
{
[self fetchUserInfo];
}
}
}];
you can get facebook user information as bellow
-(void)fetchUserInfo
{
if ([FBSDKAccessToken currentAccessToken])
{
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"id,name,link,first_name, last_name, picture.type(large), email, birthday, bio ,location ,friends ,hometown , friendlists"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error)
{
NSString *photostring=[[[result valueForKey:#"picture"] objectForKey:#"data"] valueForKey:#"url"];
photostring = [photostring stringByReplacingOccurrencesOfString:#"&" withString:#"%26"];
NSLog(#"all data here is:%#",result);
NSLog(#"username is :%#",[result valueForKey:#"name"]);
NSLog(#"PhotoUrl is :%#",photostring);
NSLog(#"mail id is :%#",[result valueForKey:#"email"]);
}
}];
}
}
Good luck with your project
Firstly, you must put this code where login process start like bellow
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"public_profile", #"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error)
{
// There is an error here.
}
else
{
if(result.token) // This means if There is current access token.
{
// Token created successfully and you are ready to get profile info
[self getFacebookProfileInfo];
}
}
}];
if login successful , implement this method to get user's public profile
-(void)getFacebookProfileInfos {
FBSDKGraphRequest *requestMe = [[FBSDKGraphRequest alloc]initWithGraphPath:#"me" parameters:nil];
FBSDKGraphRequestConnection *connection = [[FBSDKGraphRequestConnection alloc] init];
[connection addRequest:requestMe completionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if(result)
{
if ([result objectForKey:#"email"]) {
NSLog(#"Email: %#",[result objectForKey:#"email"]);
}
if ([result objectForKey:#"first_name"]) {
NSLog(#"First Name : %#",[result objectForKey:#"first_name"]);
}
if ([result objectForKey:#"dob"]) {
NSLog(#"Date of birth : %#",[result objectForKey:#"dob"]);
}
if ([result objectForKey:#"id"]) {
NSLog(#"User id : %#",[result objectForKey:#"id"]);
}
}
}];
[connection start];
}
you can also follow this link get facbook user information
or you can get facebook user information as bellow
if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
NSString *firstName = user.first_name;
NSString *lastName = user.last_name;
NSString *bateOfBirth = user.bate_Of_Birth;
NSString *facebookId = user.id;
NSString *email = [user objectForKey:#"email"];
NSString *imageUrl = [[NSString alloc] initWithFormat: #"http://graph.facebook.com/%#/picture?type=large", facebookId];
}
}];
}