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);
}
}];
}
}
}];
}
Related
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 followed the instructions provided by Facebook to add a "Login with Facebook" button in my app. In order to populate additional view controllers, I will need to pull data from the logged in user such as name and email. However, there does not seem to be a way to access this data.
For reference, the following code is pasted directly from Facebook instructions.
FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];
loginButton.center = self.view.center;
loginButton.readPermissions = #[#"public_profile", #"email", #"user_friends"];
[self.view addSubview:loginButton];
Any assistance is much appreciated. Thanks!
If you have Custom Facebook Button Then Just Call the Below Code On Button action:
I already checked it and it works fine for me.
See the reference:
-(void)FBLogin{
NSMutableDictionary *fbResultData;
fbResultData =[[NSMutableDictionary alloc]init];
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(#"Logged in");
if ([FBSDKAccessToken currentAccessToken])
{
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me?fields=id,name,age_range,birthday,devices,email,gender,last_name,family,friends,location,picture" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString * accessToken = [[FBSDKAccessToken currentAccessToken] tokenString];
NSLog(#"fetched user:%# ,%#", result,accessToken);
if ([result objectForKey:#"email"]) {
[fbResultData setObject:[result objectForKey:#"email"] forKey:#"email"];
}
if ([result objectForKey:#"gender"]) {
[fbResultData setObject:[result objectForKey:#"gender"] forKey:#"gender"];
}
if ([result objectForKey:#"name"]) {
NSArray *arrName;
arrName=[[result objectForKey:#"name"] componentsSeparatedByString:#" "];
[fbResultData setObject:[arrName objectAtIndex:0] forKey:#"name"];
}
if ([result objectForKey:#"last_name"]) {
[fbResultData setObject:[result objectForKey:#"last_name"] forKey:#"last_name"];
}
if ([result objectForKey:#"id"]) {
[fbResultData setObject:[result objectForKey:#"id"] forKey:#"id"];
}
[fbResultData setObject:accessToken forKey:#"Access Token"]; //m
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:#"me/picture?type=large&redirect=false"]
parameters:nil
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if (!error){
if ([[result objectForKey:#"data"] objectForKey:#"url"]) {
[fbResultData setObject:[[result objectForKey:#"data"] objectForKey:#"url"] forKey:#"picture"];
}
NSLog(#"Final data of FB login********%#",fbResultData);
} }];
}
else {
NSLog(#"result: %#",[error description]);
UIAlertController *alert=[UIAlertController alertControllerWithTitle:NSLocalizedString(#"Error", nil) message:[error description] preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *alertBtnOk=[UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
{
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:alertBtnOk];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
else{
[[FBSDKLoginManager new] logOut];
}
}
}];}
In fbResultData you will get all user data, but don't forget to import these files:
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
This code is useful for getting Facebook login user data and his/her friend's list which are not using your app:
-(void)FBLogin{
NSMutableDictionary *fbResultData;
fbResultData =[[NSMutableDictionary alloc]init];
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(#"Logged in");
if ([FBSDKAccessToken currentAccessToken])
{
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me?fields=id,name,age_range,birthday,devices,email,gender,last_name,family,invitable_friends,location,picture" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString * accessToken = [[FBSDKAccessToken currentAccessToken] tokenString];
NSLog(#"fetched user:%# ,%#", result,accessToken);
if ([result objectForKey:#"email"]) {
[fbResultData setObject:[result objectForKey:#"email"] forKey:#"email"];
}
if ([result objectForKey:#"gender"]) {
[fbResultData setObject:[result objectForKey:#"gender"] forKey:#"gender"];
}
if ([result objectForKey:#"name"]) {
NSArray *arrName;
arrName=[[result objectForKey:#"name"] componentsSeparatedByString:#" "];
[fbResultData setObject:[arrName objectAtIndex:0] forKey:#"name"];
}
if ([result objectForKey:#"last_name"]) {
[fbResultData setObject:[result objectForKey:#"last_name"] forKey:#"last_name"];
}
if ([result objectForKey:#"id"]) {
[fbResultData setObject:[result objectForKey:#"id"] forKey:#"id"];
}
[fbResultData setObject:accessToken forKey:#"Access Token"]; //m
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:[NSString stringWithFormat:#"me/picture?type=large&redirect=false"]
parameters:nil
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,
id result,
NSError *error) {
if (!error){
if ([[result objectForKey:#"data"] objectForKey:#"url"]) {
[fbResultData setObject:[[result objectForKey:#"data"] objectForKey:#"url"] forKey:#"picture"];
}
NSLog(#"Final data of FB login********%#",fbResultData);
} }];
}
else {
NSLog(#"result: %#",[error description]);
UIAlertController *alert=[UIAlertController alertControllerWithTitle:NSLocalizedString(#"Error", nil) message:[error description] preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *alertBtnOk=[UIAlertAction actionWithTitle:#"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action)
{
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:alertBtnOk];
[self presentViewController:alert animated:YES completion:nil];
}
}];
}
else{
[[FBSDKLoginManager new] logOut];
}
}
}];}
I want to get Username and Profile picture usig FBSDKLoginKit.
How to get it ?
My code is here.
pod 'FBSDKLoginKit', '~> 4.7'
- (IBAction)fbLoginActionClicked:(id)sender
{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: #[#"public_profile"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(#"Process error");
}
else if (result.isCancelled)
{
NSLog(#"Cancelled");
}
else
{
NSLog(#"Logged in");
}
}];
}
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{ #"fields" : #"id,name,picture.width(100).height(100)"}]startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString *nameOfLoginUser = [result valueForKey:#"name"];
NSString *imageStringOfLoginUser = [[[result valueForKey:#"picture"] valueForKey:#"data"] valueForKey:#"url"];
NSURL *url = [[NSURL alloc] initWithURL: imageStringOfLoginUser];
[self.imageView setImageWithURL:url placeholderImage: nil];
}
}];
}
Use FBSDKGraphRequest like the following code to get username and profile picture of Facebook user.
Once you are logged in, add the following code:
NSLog(#"Logged in");
if ([result.grantedPermissions containsObject:#"public_profile"]) {
if ([FBSDKAccessToken currentAccessToken]) {
NSMutableDictionary* parameters = [NSMutableDictionary dictionary];
[parameters setValue:#"name,picture.type(large)" forKey:#"fields"];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:parameters]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error)
{
NSLog(#"fetched user:%#", result);
NSString *name = [[result valueForKey:#"name"] lowercaseString];
NSString *username = [name stringByReplacingOccurrencesOfString:#" " withString:#""];
NSArray *picture_arr = [result objectForKey:#"picture"];
NSArray *data_arr = [picture_arr valueForKey:#"data"];
NSString *profile_pic = [data_arr valueForKey:#"url"];
}
}];
- (IBAction)fbLoginActionClicked:(id)sender
{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login
logInWithReadPermissions: #[#"public_profile"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(#"Process error");
}
else if (result.isCancelled)
{
NSLog(#"Cancelled");
}
else
{
NSLog(#"Logged in %# %#", result.token.userID, result.token.tokenString);
[self fetchUserInfo];
}
}];
}
-(void)fetchUserInfo
{
if ([FBSDKAccessToken currentAccessToken])
{
NSLog(#"Token is available : %#",[[FBSDKAccessToken currentAccessToken]tokenString]);
[[[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)
{
NSLog(#"resultis:%#",result);
}
else
{
NSLog(#"Error %#",error);
}
}];
}
}
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];
}
}];
}
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
}
}];
}
}