How to get username from Facebook SDK 4.0 in ios - ios

How to get username from facebook sdk 4.0 in iOS?

-(IBAction)LoginWithFacebook:(id)sender {
if ([FBSDKAccessToken currentAccessToken]) {
[self getDetailsAndLogin];
}
else{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
// Process error
NSLog(#"%#",error.description);
} else if (result.isCancelled) {
// Handle cancellations
NSLog(#"Result Cancelled!");
} else {
// If you ask for multiple permissions at once, you
// should check if specific permissions missing
if ([result.grantedPermissions containsObject:#"email"]) {
// Do work
[self getDetailsAndLogin];
}
}
}];
}
}
-(void)getDetailsAndLogin{
if (LOGGING) {
return;
}
LOGGING = YES;
[super startLoader];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSString *userID = [[FBSDKAccessToken currentAccessToken] userID];
NSString *userName = [result valueForKey:#"name"];
NSString *email = [result valueForKey:#"email"];
NSString *userImageURL = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?type=large", [[FBSDKAccessToken currentAccessToken] userID]];
[User LoginWithFbId:userID Username:userName Email:email ImageUrl:userImageURL success:^(User *response) {
[super stopLoader];
UIStoryboard* sb = [UIStoryboard storyboardWithName:#"Main" bundle:nil];
TabViewController *TabVC = [sb instantiateViewControllerWithIdentifier:#"TabViewController"];
[self.navigationController pushViewController:TabVC animated:YES];
} failure:^(NSString *error) {
LOGGING = NO;
[super stopLoader];
[super showAlertWithTitle:#"Cannot Login" Message:error];
}];
}
else{
LOGGING = NO;
[super stopLoader];
NSLog(#"%#",error.localizedDescription);
}
}];
}
here LoginWithFacebook is a button action to get data . Do not forget to import SDK of FBSession which you can get easily from here . Register your app create a key and import this key in your application.
Happy coding

You can´t get the username anymore:
/me/username is no longer available.
Source: https://developers.facebook.com/docs/apps/changelog#v2_0_graph_api
If you want to detect returning users, use the (App Scoped) ID instead.

Easiest Answer would be to check the following after user is logged in:
if ([FBSDKProfile currentProfile])
{
NSLog(#"User name: %#",[FBSDKProfile currentProfile].name);
NSLog(#"User ID: %#",[FBSDKProfile currentProfile].userID);
}

*Use my code its works excellent.
- (IBAction)tapon_facebookLogin:(id)sender {
if ([FBSDKAccessToken currentAccessToken]) {
// TODO:Token is already available.
NSLog(#"FBSDKAccessToken alreay exist");
[self fetchFbUserInfo];
}else{
NSLog(#"FBSDKAccessToken not exist");
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithReadPermissions:#[#"email",#"public_profile"]
fromViewController:self
handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
//TODO: process error or result
if (!error) {
NSLog(#"result %#",result.debugDescription);
[self fetchFbUserInfo];
}else{
NSLog(#"errorfacebook %#",error.description);
}
}];
}}
-(void)fetchFbUserInfo{
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 ,location ,friends ,hometown , friendlists"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error)
{
NSLog(#"resultisfetchFbUserInfo:%#",result);
}
else
{
NSLog(#"ErrorfetchFbUserInfo %#",error);
}
}];}}

Related

Facebook Login Status Check Issue

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

FBSDK findByGraphPath (me) doesn't return an email, even with permissions and explicit fields

I try to fetch at least id, username and email from a logged in Facebook user. I first login using the permission type: Email. And if succeeded try to fetch an FBSDKGraphRequest, which returns every possible value but email.
I tried adding permissions like public_profile as well, but in any case I try, I do not get email. I looked in the developers dashboard, and email seems to be approved by default.
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithReadPermissions:#[#"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
return;
} else if (result.isCancelled) {
return;
}
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"id, name, gender, first_name, last_name, locale, email"}];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (error) {
NSLog(#"Error: %#", error);
return;
}
NSLog(#"Fetched user: %#", result);
}];
}];
Your code should be like this
-(void)loginWithFacebookButtonTouchUpInside
{
if(![FBSDKAccessToken currentAccessToken])
{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"email",#"public_profile"] fromViewController:nil handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
// Process error
}
else if (result.isCancelled)
{
// Handle cancellations
}
else
{
// If you ask for multiple permissions at once, you
// should check if specific permissions missing
[self userLoggedIn];
}
}];
}else{
//error "Authentication is not done"
}
}
- (void)userLoggedIn
{
[FBSDKProfile enableUpdatesOnAccessTokenChange:NO];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"name, email,first_name,last_name"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id userInfo, NSError *error) {
if (!error) {
{
}
}
}];
}
I just had the same problem and I was lucky enough to find the solution in the comment. It is given by CBroe. I think that this should be posted as an answer.
So... in my case the problem was that the user had not confirmed his email. Once I've confirmed it I received the email from Facebook. All the acknowledgemnts are to CBroe
Use the following code on Login Button click.
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager setLoginBehavior:FBSDKLoginBehaviorSystemAccount];
[loginManager logInWithReadPermissions:#[#"public_profile", #"email", #"user_friends"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
[loginManager logOut];
}
else if (result.isCancelled)
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
[loginManager logOut];
}
else
{
if ([result.grantedPermissions containsObject:#"publish_actions"])
{
NSTimeInterval addTimeInterval = 60*60*24*365*50;
NSDate *expireDate = [[NSDate date] dateByAddingTimeInterval:addTimeInterval];
NSDate *refreshDate = [[NSDate date] dateByAddingTimeInterval:addTimeInterval];
FBSDKAccessToken *newAccessToken = [[FBSDKAccessToken alloc] initWithTokenString:[[FBSDKAccessToken currentAccessToken] tokenString] permissions:nil declinedPermissions:nil appID:FACEBOOK_ID userID:[[FBSDKAccessToken currentAccessToken] userID] expirationDate:expireDate refreshDate:refreshDate];
[FBSDKAccessToken setCurrentAccessToken:newAccessToken];
[self FacebookUserInfo];
}
else
{
[loginManager logInWithPublishPermissions:#[#"publish_actions"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
[loginManager logOut];
}
else if (result.isCancelled)
{
[MBProgressHUD hideHUDForView:self.view animated:YES];
[loginManager logOut];
}
else
{
NSTimeInterval addTimeInterval = 60*60*24*365*50;
NSDate *expireDate = [[NSDate date] dateByAddingTimeInterval:addTimeInterval];
NSDate *refreshDate = [[NSDate date] dateByAddingTimeInterval:addTimeInterval];
FBSDKAccessToken *newAccessToken = [[FBSDKAccessToken alloc] initWithTokenString:[[FBSDKAccessToken currentAccessToken] tokenString] permissions:nil declinedPermissions:nil appID:FACEBOOK_ID userID:[[FBSDKAccessToken currentAccessToken] userID] expirationDate:expireDate refreshDate:refreshDate];
[FBSDKAccessToken setCurrentAccessToken:newAccessToken];
[self FacebookUserInfo];
}
}];
}
}
}];
Once you get Access Token call following method.
- (void)FacebookUserInfo
{
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields":#"name,email,first_name,last_name"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
if (!error)
{
NSDictionary *dict = #{#"id":result[#"id"],
#"name":result[#"first_name"],
#"email":result[#"email"]
};
[self saveData:dict];
}
else
{
}
}];
}
May be this is helpful for you.
Confirm your email on Facebook. The problem will be resolved.

Get User name and Profile picture using FBSDKLoginkit

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

Getting user's Personal info from FacebookSDK in iOS

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

Facebook SDK iOS use user data

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

Resources