Facebook iOS SDK not returning user email - iphone

I am trying to get access to some user's info, including email. For this purpose, I use the Graph API to call this method:
[facebook requestWithGraphPath:#"me" andDelegate:self];
It returns the user info, without the email information (the birthday is also missing). I setted all permissions and tested with more than one account (which has email and birthday as a public information), and accepted all the dialog's requests.
Here is my init:
if(!facebook) {
facebook = [[Facebook alloc] initWithAppId:[self _APP_KEY] andDelegate:self];
NSArray *array = [NSArray arrayWithObjects: #"email", #"user_birthday", #"publish_stream", #"offline_access", nil];
[self setPermissions:array];
}
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"] && [defaults objectForKey:#"FBExpirationDateKey"]) {
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
if (![facebook isSessionValid]) {
[facebook authorize:permissions];
}
else {
[self getUserInfo];
}
The login callback:
- (void)fbDidLogin {
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:[facebook accessToken] forKey:#"FBAccessTokenKey"];
[defaults setObject:[facebook expirationDate] forKey:#"FBExpirationDateKey"];
[defaults synchronize];
[self getUserInfo];
}
The getUserInfo method:
- (void) getUserInfo {
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
The request callback:
- (void)request:(FBRequest *)request didLoad:(id)result {
if ([result isKindOfClass:[NSDictionary class]]) {
NSDictionary* json = result;
NSLog(#"-> %#", json);
}
}
The result is the following:
-> {
"first_name" = EDITED (my name);
gender = male;
hometown = {
id = 111072692249998;
name = "Porto Alegre";
};
id = 653099452;
languages = (
{
id = 104034306299811;
name = "Brazilian Portuguese";
},
{
id = 106059522759137;
name = English;
}
);
"last_name" = EDITED (my last name);
link = EDITED (my profile);
locale = "en_US";
location = {
id = 112047398814697;
name = "S\U00e3o Paulo, Brazil";
};
name = EDITED (my name);
timezone = "-3";
"updated_time" = "2012-04-25T13:36:51+0000";
verified = 1;
}
As you can see, there is no information about the user's email. Am I missing some step? Any ideias?
Thanks in advance

Try to use this, it works in my case
facebook = [[Facebook alloc] initWithAppId:[self _APP_KEY] andDelegate:self];
[facebook authorize:[NSArray arrayWithObjects:#"email",nil]];

Try this
permissions = [[NSArray alloc] initWithObjects:#"offline_access",#"email",nil];

you can get the user email like this .. after the fbDidlogin fired call this method
- (void)fetchUserDetails {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"SELECT uid, name, pic, email FROM user WHERE uid=me()", #"query",nil];
[fb requestWithMethodName:#"fql.query"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}
and in the request:(FBRequest *)request didLoad you will do something like this:
- (void)request:(FBRequest *)request didLoad:(id)result
{
if([request.url rangeOfString:#"fql.query"].location !=NSNotFound)
{
if ([result isKindOfClass:[NSArray class]] && [result count]>0) {
result = [result objectAtIndex:0];
}
if ([result objectForKey:#"email"]) {
NSLog(#"%#",[result objectForKey:#"email"]);
}
}
}
Enjoy :)

1) Give the permission to get the Email and the info etc...
// You must ALWAYS ask for public_profile permissions when opening a session
[FBSession openActiveSessionWithReadPermissions:#[#"public_profile",#"user_videos",#"email"]
allowLoginUI:YES
completionHandler:
^(FBSession *session, FBSessionState state, NSError *error)
{
// Retrieve the app delegate
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
// Call the app delegate's sessionStateChanged:state:error method to handle session state changes
[appDelegate sessionStateChanged:session state:state error:error];
}];
2) to get the Email where you want...
if (FBSession.activeSession.isOpen)
{
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error)
{
if (!error)
{
NSString *userEmail = [user objectForKey:#"email"];
}
[tblSettingVw reloadData];
}];
}
Note : User Dictionary will Return following
{
"first_name" =;
gender =;
id =;
"last_name" =;
link = "";
locale = "";
name = "";
timezone = "";
"updated_time" = "";
verified = ;
}

All facebook accounts which are verified through Phone Number instead of email will get NULL for [user objectForKey:#"email"]

You can only access an user's email if you get the user's authorization for it.
The public graph does not provide this information.
You should read this: https://developers.facebook.com/docs/guides/web/#login

You need to ask permission to the user for this information via:
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_birthday",
nil];
return [FBSession openActiveSessionWithPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
Here's all the info you need, just follow this tutorials
First, this one: Facebook Login
And then, this one: Fetch user data

Related

Null access token for facebook

Hi been struggling with this for the past 2 days. I never had the issue before but the access token being returned from facebook is always null no matter what I do.
The code used is from facebook connect IOS sdk. I used the exact same code in other apps but had no issues but for some reason this doesn't work now.
There are also no error codes being printed.
Thanks.
I use in sessionChangeState, this code:
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary *result, NSError *error) {
NSLog(#"access Token %#", FBSession.activeSession.accessToken);
}];
And it return me access token, try it!
Try this code.You will get access token through self.facebook.accessToken .
call facebookbtnclicked method at view did load or anywhere to get access token.
facebook = [[Facebook alloc] initWithAppId:#"227757844008650"];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"]
&& [defaults objectForKey:#"FBExpirationDateKey"])
{
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
-(void)facebookbtnclicked
{
NSLog(#"facebook btn clicked");
[self loginToFacebook:self];
}
- (BOOL) isFaceBookLoggedIn
{
if (self.facebook.accessToken)
{
return YES;
}
else {
return NO;
}
}
- (void) logoutFromFacebook: (id) logoutDelegate
{
fbServiceRequestingobj = logoutDelegate;
[facebook logout:self];
}
- (void)loginToFacebook:(id) loginDelegate
{
NSLog(#"login facebook method");
fbServiceRequestingobj = loginDelegate;
NSArray* permissions = [[NSArray alloc] initWithObjects:
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
}
-(void) getuserdata
{
NSLog(#"[appDelegate getuserdata]");
if (fbServiceRequestingobj)
{
fbServiceRequestingobj = nil;
}
[facebook requestWithGraphPath:#"me" andDelegate:self];
[facebook requestWithGraphPath:#"me/friends" andDelegate:self];
}
- (void)fbDidLogout
{
NSLog(#"Did Logout");
if (fbServiceRequestingobj)
{
if ([fbServiceRequestingobj respondsToSelector:#selector(fbDidLogout)])
{
[fbServiceRequestingobj performSelector:#selector(fbDidLogout)];
}
}
fbServiceRequestingobj = nil;
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
if (fbServiceRequestingobj)
{
if ([fbServiceRequestingobj respondsToSelector:#selector(request:didFailWithError:)])
{
[fbServiceRequestingobj request:request didFailWithError:error];
}
}
fbServiceRequestingobj = nil;
}
-(void)fbDidNotLogin:(BOOL)cancelled
{
if (fbServiceRequestingobj)
{
if ([fbServiceRequestingobj respondsToSelector:#selector(fbDidNotLogin:)])
{
//[fbServiceRequestingobj fbDidNotLogin:cancelled];
}
}
fbServiceRequestingobj = nil;
}
- (void)fbDidLogin
{
NSLog(#"fbDidLogin");
//[facebook requestWithGraphPath:#"me/friends" andDelegate:self];
NSLog(#"accesstoken########%#",self.facebook.accessToken);
}
- (void)requestFinished:(ASIHTTPRequest *)request
{
count++;
NSError *error = [request error];
if (!error)
{
NSString *response = [request responseString];
NSDictionary *respdic=[response JSONValue];
if(![[respdic valueForKey:#"id"] isEqualToString:#""])
{
UIAlertView *alert1=[[UIAlertView alloc] initWithTitle:#"" message:#"Photo posted successfully." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil, nil];
[alert1 show];
}
}
}
- (void)request:(FBRequest *)request didLoad:(id)result
{
if ([result isKindOfClass:[NSArray class]])
{
result = [result objectAtIndex:0];
}
if ([result isKindOfClass:[NSDictionary class]])
{
}
}
if ([result isKindOfClass:[NSData class]])
{
UIImage *profilePicture = [[UIImage alloc] initWithData: result];
}
if (fbServiceRequestingobj)
{
if ([fbServiceRequestingobj respondsToSelector:#selector(request:didLoad:)])
{
[fbServiceRequestingobj request:request didLoad:result];
}
}
fbServiceRequestingobj = nil;
};

Facebook access token error on iphone

I am trying to get name of facebook user in my app but I am getting
{"error":{"message":"An active access token must be used to query information about the current user.","type":"OAuthException","code":2500}}
My code is :-
In viewdidload
facebook = [[Facebook alloc] initWithAppId:#"233350100117670" andDelegate:self];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"] && [defaults objectForKey:#"FBExpirationDateKey"])
{
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
NSArray *permissions = [[NSArray arrayWithObjects:#"read_stream", #"publish_stream", #"offline_access",nil] retain];
[facebook authorize:permissions];
if (![facebook isSessionValid])
{
[facebook authorize:nil];
}
After that:-
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
NSLog(#"%#", [error localizedDescription]);
NSLog(#"Err details: %#", [error description]);
}
- (void)request:(FBRequest*)request didLoadRawResponse:(NSData*)data
{
NSString *response = [[NSString alloc] initWithData: data encoding: NSUTF8StringEncoding];
NSLog(#"%#", response);
[response release];
}
- (void) request:(FBRequest*)request didLoad:(id)result
{
if ([result isKindOfClass:[NSDictionary class]])
{
NSString *email = [result objectForKey: #"email"];
fbUserName = [result objectForKey: #"name"];
NSString *facebookId = [result objectForKey: #"id"];
NSString* title=[NSString stringWithFormat:#"%# has won a gold medal on Olympedia quiz",fbUserName];
NSMutableDictionary *params =
[NSMutableDictionary dictionaryWithObjectsAndKeys:title, #"name",#"Feed Dialogs of Olympedia.", #"caption",#"Check out Olmpedia Dialogs.", #"description",#"http://www.facebook.com/olympedia", #"link",#"http://bit.ly/PdpRSD", #"picture",nil];
[facebook dialog:#"feed" andParams:params andDelegate:self];
}
}
And on share button click:-
- (IBAction)shareOnFacebook:(id)sender
{
NSLog(#"Posting message");
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
Please help as I am trying to solve this for hours.strong text

Getting Facebook username for iOS

I'm using the following to get the Facebook username:
[facebook requestWithGraphPath:#"me" andDelegate:facebook];
from my understanding I then have to use something like the following request to
- (void)request:(FBRequest *)request didLoad:(id)result {
NSLog(#"Result: %#", result);
NSDictionary *userInfo = (NSDictionary *)result;
userName = [userInfo objectForKey:#"name"];
fb_id = [userInfo objectForKey:#"id"];
}
my question is how do I call this request method from another method?
thanks for any help
check my function below to fetch user data id,pic and name
- (void)fetchUserDetails {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"SELECT uid, name, pic FROM user WHERE uid=me()", #"query",nil];
[fb requestWithMethodName:#"fql.query"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}
and in the delegate method you will log the name like this
- (void)request:(FBRequest *)request didLoad:(id)result
{
if ([result isKindOfClass:[NSArray class]] && [result count]>0) {
result = [result objectAtIndex:0];
}
if ([result objectForKey:#"name"])
NSString *userName = [result objectForKey:#"name"];
NSLog(#"%#",userName);
}

Get friends info from Facebook on my iPhone app

I am developing an application for iPhone that uses facebook.
I need to get my data (the data of current user).
I'm sure I made the correct login and have obtained the proper permissions.
Now,
I want a NSArray with the data and make a print with NSLog oh this data.
I have made this for the friendlist and i have no problem:
-(IBAction)friendsInfo:(id)sender{
// get the logged-in user's friends
[facebook requestWithGraphPath:#"me/friends" andDelegate:self];
}
- (void)request:(FBRequest *)request didLoad:(id)result {
//ok so it's a dictionary with one element (key="data"), which is an array of dictionaries, each with "name" and "id" keys
items = [(NSDictionary *)result objectForKey:#"data"];
for (int i=0; i<[items count]; i++) {
NSDictionary *friend = [items objectAtIndex:i];
long long fbid = [[friend objectForKey:#"id"]longLongValue];
NSString *name = [friend objectForKey:#"name"];
NSLog(#"id: %lld - Name: %#", fbid, name);
}
}
But for my info the same method not work:
-(IBAction)myInfo:(id)sender{
// get information about the currently logged in user
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
Can someone help me?
use this function to get your faceBook Info (logged in user info)
- (void)fetchUserDetails {
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"SELECT uid, name, pic FROM user WHERE uid=me()", #"query",nil];
[fb requestWithMethodName:#"fql.query"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
}
-(void)addList:(FBSession *)session {
NSString* fql = [NSString stringWithFormat:
#"select uid from user where uid == %lld", session.uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:#"query"];
sessionView = session;
[[FBRequest requestWithDelegate:self] call:#"facebook.friends.get" params:params];
}
- (void)request:(FBRequest*)request didLoad:(id)result {
if(myList==nil) {
NSArray* users = result;
myList =[[NSArray alloc] initWithArray: users];
for(NSInteger i=0;i<[users count];i++) {
NSDictionary* user = [users objectAtIndex:i];
NSString* uid = [user objectForKey:#"uid"];
NSString* fql = [NSString stringWithFormat:
#"select name from user where uid == %#", uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:#"query"];
[[FBRequest requestWithDelegate:self] call:#"facebook.fql.query" params:params];
}
}
else {
NSArray* users = result;
NSDictionary* user = [users objectAtIndex:0];
NSString* name = [user objectForKey:#"name"];
txtView.text=[NSString localizedStringWithFormat:#"%#%#,\n",txtView.text,name];
}
}
-(IBAction)getMeFriendsButtonPressed:(id)sender {
FbGraphResponse *fb_graph_response = [fbGraph doGraphGet:#"me/friends" withGetVars:nil];
NSLog(#"getMeFriendsButtonPressed: %#", fb_graph_response.htmlResponse);
NSDictionary *DictTmp = [fb_graph_response.htmlResponse JSONValue];
NSMutableArray *myFriendList=[[DictTmp objectForKey:#"data"];
}
NSString* fql = [NSString stringWithFormat:#"select uid,name from user where uid == %lld", session.uid];
NSDictionary* params = [NSDictionary dictionaryWithObject:fql forKey:#"query"];
[[FBRequest requestWithDelegate:self] call:#"facebook.fql.query" params:params];
[[FBRequest requestWithDelegate:self] call:#"facebook.friends.get" params:params];

why fbdidlogin didn't call?

- (id)init {
if (self == [super init]) {
facebook = [[Facebook alloc] initWithAppId:kAppId];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
if ([defaults objectForKey:#"FBAccessTokenKey"]
&& [defaults objectForKey:#"FBExpirationDateKey"]) {
facebook.accessToken = [defaults objectForKey:#"FBAccessTokenKey"];
facebook.expirationDate = [defaults objectForKey:#"FBExpirationDateKey"];
}
if (![facebook isSessionValid]) {
permissions = [[NSArray arrayWithObjects:
#"read_stream", #"user_birthday",
#"publish_stream", nil] retain];
[facebook authorize:permissions delegate:self];
}
[self login];
}
return self;
}
- (void)login {
if (![_session isConnected]) {
[self postToWall];
}
if (![facebook isSessionValid]) {
[facebook authorize:permissions delegate:self];
}
}
- (void)fbdidLogin {
[[NSUserDefaults standardUserDefaults] setObject:self.facebook.accessToken forKey:#"FBAccessToken"];
[[NSUserDefaults standardUserDefaults] setObject:self.facebook.expirationDate forKey:#"FBExpirationDate"];
// User has logged in to Facebook, now get their userId from Facebook
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
-(void)postToWall
{
SBJSON *jsonWriter = [[SBJSON new] autorelease];
NSDictionary *actionLinks = [NSArray arrayWithObjects:[NSDictionary dictionaryWithObjectsAndKeys:
#"Always Running",#"text",#"http://itsti.me/",#"href", nil], nil];
NSString *actionLinksStr = [jsonWriter stringWithObject:actionLinks];
NSDictionary *attachment = [NSDictionary dictionaryWithObjectsAndKeys:
#"Your Happiness!", #"name",
#"asda", #"caption",
#"asdf", #"description",
nil];
NSString *attachmentStr = [jsonWriter stringWithObject:attachment];
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Share on Facebook", #"user_message_prompt",
actionLinksStr, #"action_links",
attachmentStr, #"attachment",
nil];
[facebook dialog:#"stream.publish" andParams:params andDelegate:self];
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
return [facebook handleOpenURL:url];
}
This is my methods for calling facebook dialog boxes.But every time when i click to score for publishing;The permission box came first.I need to give permission after that the publish dialog box comes.I want to give permission ones and i want it to save it;after saving it i don't wanna see the permission box ever again.How can i do it?What is wrong with my code?
edit:
My access token and expiration date is null i guess thats because of this.
A few things to check, you call the method login handling method "fbdidLogin" instead of fbDidLogin. This is case sensitive.
Make sure in your view controller header file that you added FBSessionDelegate as one of the protocols you support. That could be a reason fbDidLogin is not called. You could always add an NSLog to verify that the fbDidLogin method is reached.
You need to implement Facebook's Single-Sign-On feature.
http://developers.facebook.com/docs/guides/mobile/#ios
This link has the step-by-step guide for implementing SSO, if you follow it carefully your App will request for permission once, then it will never request permission again (until the user remove your App)
Note that, you will need to go to www.facebook.com and use the "Developer Tools" to create a new Facebook App, you will be the admin of the app, and you will have your AppID, you will need this too.