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
Related
Hi there I'm dealing with a big issue at least for me, I have implemented an older version of Facebook SDK I have many features in my app using this SDK and updated to the most recent version will take a few days, and I don't have time now to do that so what I want to do is simple, I just want to receive the parameters email, last_name and name but Facebook just returns me the name and the id, so could yo have any idea or I am doing something wrong?. Thanks in advance.
- (void)requestUserInfo{
// We will request the user's public picture and the user's birthday
// These are the permissions we need:
NSArray *permissionsNeeded = #[#"public_profile", #"email"];
// Request the permissions the user currently has
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded)
{
// If there's one, just open the session silently, without showing the user the login UI
[FBSession openActiveSessionWithReadPermissions:#[#"public_profile", #"email"]
allowLoginUI:NO
completionHandler:^(FBSession *session, FBSessionState state, NSError *error)
{
NSLog(#"%#", session.accessTokenData.accessToken);
}];
}
[FBRequestConnection startWithGraphPath:#"me"
parameters:[NSDictionary dictionaryWithObject:#"id,email,name,last_name" forKey:#"fields"]
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error){
// Parse the list of existing permissions and extract them for easier use
NSMutableArray *currentPermissions = [[NSMutableArray alloc] init];
NSArray *returnedPermissions = (NSArray *)[result data];
for (NSDictionary *perm in returnedPermissions) {
if ([[perm objectForKey:#"status"] isEqualToString:#"granted"]) {
[currentPermissions addObject:[perm objectForKey:#"permission"]];
}
}
//NSLog(#"Needed: %#", permissionsNeeded);
//NSLog(#"Current: %#", currentPermissions);
NSMutableArray *requestPermissions = [[NSMutableArray alloc] initWithArray:permissionsNeeded copyItems:YES];
[requestPermissions removeObjectsInArray:currentPermissions];
//NSLog(#"Asking: %#", requestPermissions);
// If we have permissions to request
if ([requestPermissions count] > 0){
// Ask for the missing permissions
[FBSession.activeSession
requestNewReadPermissions:requestPermissions
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// Permission granted, we can request the user information
[self makeRequestForUserData];
} else {
// An error occurred, we need to handle the error
// Check out our error handling guide: https://developers.facebook.com/docs/ios/errors/
NSLog(#"error %#", error.description);
}
}];
} else {
// Permissions are present
// We can request the user information
[self makeRequestForUserData];
}
} else {
// An error occurred, we need to handle the error
// Check out our error handling guide: https://developers.facebook.com/docs/ios/errors/
NSLog(#"error %#", error.description);
}
}];
}
And this is the info:
llega el objeto:{
id = 10210924411602727;
name = "Del Mar Sal";
}
Below i attached the FB Login & Fetch details from Facebook. Try it that code & Compare.
- (IBAction)facebook_BtnTap:(id)sender {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"public_profile",#"email"]handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error) {
NSLog(#"Process error");
} else if (result.isCancelled) {
NSLog(#"Cancelled");
} else {
if ([result.grantedPermissions containsObject:#"email"]) {
// Do work
[self GetUserDetails];
}
}
}];
}
-(void)GetUserDetails
{
BOOL LOGGING;
if (LOGGING) {
return;
}
LOGGING = YES;
// [super startLoader];
if ([FBSDKAccessToken currentAccessToken])
{
NSLog(#“Check Already login");
//[FBSession openActiveSessionWithAllowLoginUI: YES];
// [self back:nil];
// return;
}
NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
[parameters setValue:#"id,name,email,first_name,last_name,birthday,picture.type(large),location,hometown,gender" forKey:#"fields"];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:parameters]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString* email = [result objectForKey:#"email"];
NSString* fname = [result objectForKey:#"first_name"];
NSString* lname = [result objectForKey:#"last_name"];
NSString* userName = [result objectForKey:#"name"];
NSString* gender = [result objectForKey:#"gender"];
NSDictionary* hometown=[result objectForKey:#"hometown"];
NSString* country = [hometown objectForKey:#"name"];
NSString* birthday=[result objectForKey:#"birthday"];
// NSArray* photo =[[result objectForKey:#"picture"]valueForKey:#"data"];
// NSDictionary* location = [result objectForKey:#"location"];
// NSString* city = [location valueForKey:#"name"];
// NSString* fbPhoto = [photo valueForKey:#"url"];
NSString* fid = [result objectForKey:#"id"];
}];
}
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);
}
}];
}
}
}];
}
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];
}
}];
}
How to get user name, user image, user email when login: didCompleteWithResult: err: method is called in Facebook SDK for iOS version 4.4.
I want to set these values to properties.
- (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error {
if (error) {
} else if (result.isCancelled) {
} else {
//I want get user info here and set values to properties.
self.userName =
self.userImage =
self.userEmail =
}
}
If you know other solutions, please tell me about it.
Try this
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"email",#"user_photos"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if ([result.grantedPermissions containsObject:#"email"]) {
[self fetchData]
}
}];
and in fetchData method
- (void)fetchData {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
DLog(#"fetched user:%#", result);
self.userFirstName = [result objectForKey:#"first_name"];
self.userLastName = [result objectForKey:#"last_name"];
self.userEmail = [result objectForKey:#"email"];
NSString *facebookId = [result objectForKey:#"id"];
self.userProfileImage = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large", facebookId];
DLog(#"URL=%#",self.userProfileImage);
}
}];
}
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
}
}];
}
}