Facebook SDK 3.0: how to receive user's e-mail? - ios

In the "old" FB iOS SDK I could receive user information via the following:
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"SELECT uid, name, email, pic FROM user WHERE uid=me()", #"query",
nil];
JBFacebookManager *fbManager = [JBFacebookManager getInstance];
fbManager.requestDelegate = self;
[fbManager.facebook requestWithMethodName:#"fql.query"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
How can I do this with the new FB iOS SDK 3.0? Do I need to use FBRequest or FBOpenGraphAction or FBGraphObject or a combination of those or something completely different?

if (FBSession.activeSession.isOpen) {
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
self.nameLabel.text = user.name;
self.emailLabel.text = [user objectForKey:#"email"];
}
}];
}
Because FBGraphUser doesn't have an email #property, we can't access the information like with the name (dot-syntax), however the NSDictionary still has the email kv-pair and we can access it like we would do with a normal NSDictionary.
Don't forget to ask for the email permission though:
NSArray *permissions = [[NSArray alloc] initWithObjects:#"email", nil];
[FBSession sessionOpenWithPermissions:permissions completionHandler:
^(FBSession *session, FBSessionState state, NSError *error) {
[self facebookSessionStateChanged:session state:state error:error];
}];

Once you have access to (id<FBGraphUser>)user, you could simply use, user[#"email"].

from this we can get facebook user's basic info and email id.
[FBSession openActiveSessionWithReadPermissions:#[#"basic_info",#"email"] allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState status,NSError *error){
if(error)
{
NSLog(#"Facebook Error : %#",error.localizedDescription);
}
else{
}
// Respond to session state changes,
// ex: updating the view
}];

Did you read the source code of the 3.0 SDK? There is a method that I think is identical:
- (FBRequest*)requestWithMethodName:(NSString *)methodName
andParams:(NSMutableDictionary *)params
andHttpMethod:(NSString *)httpMethod
andDelegate:(id <FBRequestDelegate>)delegate;

The easiest method for getting the info after logging in is :
-(IBAction)loginWithFacebook:(id)sender{
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 {
NSLog(#"Logged in");
[self getFacebookProfileInfos];
}
}];
}
-(void)getFacebookProfileInfos {
NSDictionary *parameters = # {#"fields": #"id, name, first_name, last_name, picture.type(large), email"};
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:parameters]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%#", result);
}
}];
}
}
You will get all the info the result.

Related

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.

Unable to post status update from ios app

I am trying to post a status on my account. I have been trying since couple of hours but can't get it working.
- (void) shareStatusUpdateButtonClicked {
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me/feed" parameters: #{ #"message" : #"hello world"}HTTPMethod:#"POST"]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"POST ID: %#",result);
}
}];
}
else {
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithPublishPermissions:#[#"publish_actions"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (!error) {
NSLog(#"Permission Granted");
NSDictionary *params = #{#"message": #"This is a test message"};
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me/feed" parameters:params HTTPMethod:#"POST"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection,id result,NSError *error) {
if(!error){
NSLog(#"RESULT %#",result);
NSLog(#"POSTED !");
}
}];
}
else{
NSLog(#"ERROR PERMISSION NOT GRANTED");
}
}
];
}
}
The problem is when i run the app, it checks if the user has permitted 'publish_actions' in the if expression, it fails then the else block executes, however it displays you have already authorised this app. Then i click Ok but the status is not posted on my facebook profile. I don't understand where i am going wrong. Any help would be apperiated.
PS: I have not asked the user to grant 'publish_actions' permission anywhere else in the code. Also i tried removing the app from facebook setting but it did't help.

How to get email id of user using facebook sdk 4.7 in ios 9

Here is my code , I am only getting user name and facebook id of user.
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 {
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%#", result);
}
}];
} NSLog(#"Results=%#",result);
NSLog(#"Logged in");
}
}];
and it also give some error like this -
-canOpenURL: failed for URL: "fbauth2:/" - error: "(null)" -canOpenURL: failed for URL: "fbauth2:/" - error: "(null)"
FBSDKLog: starting with Graph API v2.4, GET requests for /me should
contain an explicit "fields" parameter
I am using pod for Facebook sdk and it's work in iOS9.0 with xcode 7.1. Try this code
void (^sendRequestsBlock)(void) = ^{
FBSDKGraphRequest *postRequest = nil;
NSDictionary *parameters = [NSDictionary dictionaryWithObject:#"id,email,first_name,last_name,name,picture{url}" forKey:#"fields"];
postRequest = [[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:parameters HTTPMethod:#"GET"];
[postRequest startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error)
{
if (!error) {
NSDictionary *dictResult = (NSDictionary *)result;
}
}];
};
/// login start
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logOut];
NSArray *permissions = [NSArray arrayWithObjects:#"email",#"public_profile", nil];
[login logInWithReadPermissions:permissions fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
} else if (result.isCancelled) {
} else {
if ([result.grantedPermissions containsObject:#"email"]) {
sendRequestsBlock();
}
}
}]

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

Not getting email id when login via FacebookSDK.framework

In my application i am doing login with facebook via FacebookSDK.framework
- (IBAction)facebookLoginBtn1:(id)sender {
[FBSession openActiveSessionWithReadPermissions:#[#"email"] allowLoginUI:YES completionHandler:
^(FBSession *session, FBSessionState state, NSError *error) {
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
[appDelegate sessionStateChanged:session state:state error:error];
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
NSString *firstName = user.first_name;
NSString *lastName = user.last_name;
NSString *facebookId = user.id;
NSString *email = [user objectForKey:#"email"];
NSString *imageUrl = [[NSString alloc] initWithFormat: #"http://graph.facebook.com/%#/picture?type=large", facebookId];
NSLog(#"%#",email);
NSLog(#"%#",user.id);
NSLog(#"%#",imageUrl);
}
else
{
}
}];
}];
}
and code working in my old application , but i am getting only FB id and user name here.
I have tried with diffrent types of permissions and facebook id's but can not able to find out what is the problem here .
I have done whole set up perfectly in info plist and facebook developer portle.
i am getting only below response as FBGraphUser object
{
id = FB id;
name = “user name here“;}
as responce .
Here no email id i am getting.
Can any one help me out here.
Its supposed to be minor thing that i am missing.
Try This code. Based on Facebook SDK version 4.0
ViewController.m
- (IBAction)btnFacebookPressed:(id)sender {
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
// Process error
}
else if (result.isCancelled)
{
// Handle cancellations
}
else
{
if ([result.grantedPermissions containsObject:#"email"])
{
NSLog(#"result is:%#",result);
[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);
}
}];
}
}
ViewDidLoad call this method you get access token after login
[self fetchUserInfo];
pass parameter this way to get email, name etc..
#{#"fields": #"id, name, link, first_name, last_name, picture.type(large), email, birthday, bio ,location ,friends ,hometown , friendlists"}
You have to specify which fields you want to get now, the following API call does not return the email even if the user authorized that permission:
/me
This is how you get access to the email again:
/me?fields=id,email
Changelog: https://developers.facebook.com/docs/apps/changelog

Resources