Null access token for facebook - iphone

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

Related

Facebook sdk fetch friend error

I am new to iOS development. I got an error when fetching the friend from facebook by using the Facebook SDK.Here are my code.
FacebookClass
- (void)fetchFacebookFriend{
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_birthday",#"friends_hometown",
#"friends_birthday",#"friends_location",#"friends_work_history",
nil];
if (!FBSession.activeSession.isOpen) {
// if the session is closed, then we open it here, and establish a handler for state changes
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
if (error != nil) {
NSLog(#"Failed to retrive facebook friend.");
return;
}
else{
self.myArray = [[NSMutableArray alloc] init];
NSLog(#"permissions::%#",FBSession.activeSession.permissions);
FBRequest *friendRequest = [FBRequest requestForGraphPath:#"me/friends?fields=name,picture,birthday,hometown,location,work"];
[friendRequest startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
appDelegate.myFacebookArray = [[NSMutableArray alloc] init];
for (NSDictionary *fbData in [result objectForKey:#"data"]) {
NSLog(#"%#",fbData);
[self.myArray addObject:fbData];
}
}];
}
}];
return;
}
}
ViewController
- (IBAction)pickFriendPressed:(id)sender {
NSLog(#"##Begin");
[[FacebookClass sharedInstance] fetchFacebookFriend];
NSLog(#"##End");
}
Output
##Begin
##End
Json data
Please help I get the Json data after display the ##End.Thanks
Here you have a code sample that fetches the friends info:
[facebook requestWithGraphPath:#"me/friends"
andParams:[ NSDictionary dictionaryWithObjectsAndKeys:#"picture,id,name,link,gender,last_name,first_name",#"fields",nil]
andDelegate:self];
Remember to:
implement the proper delegate methods
You must call authorize before fetching the friends information. This way the user will be able to login first.
I hope this helps, cheers
Try this:
get friend list using
[FBRequest requestForMyFriends];
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection connection,NSDictionary result,NSError error) { NSArray friends = [result objectForKey:#"data"]; ......
the coding is as follow but main line is [FBRequest requestForMyFriends];
-(void)sessionStateChanged:(FBSession *)session state:(FBSessionState)state error:(NSError *)error {
switch (state) {
case FBSessionStateOpen: {
if (self != nil) {
[[FBRequest requestForMe] startWithCompletionHandler: ^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error) {
//error
}else{
FBRequest* friendsRequest = [FBRequest requestForMyFriends];
[friendsRequest startWithCompletionHandler: ^(FBRequestConnection *connection,NSDictionary* result,NSError *error) {
NSArray* friends = [result objectForKey:#"data"];
for (int i = 0; i < [arrFacebookFriends count]; i++) {
UserShare *shareObj = [arrFacebookFriends objectAtIndex:i];
[shareObj release];
shareObj = nil;
}
[arrFacebookFriends removeAllObjects];
for (NSDictionary<FBGraphUser>* friend in friends) {
UserShare *shareObj = [[UserShare alloc] init];
shareObj.userName = friend.name;
shareObj.userFullName = friend.username;
shareObj.userId = [friend.id intValue];
NSLog(#"%#",friend.id);
shareObj.userPhotoUrl = [NSString stringWithFormat:#"https://graph.facebook.com/%#/picture?", friend.id];
[arrFacebookFriends addObject:shareObj];
[shareObj release];
}
[self StopSpinner];
[tblFacebookFriends reloadData];
}];
}
}];
}
FBCacheDescriptor *cacheDescriptor = [FBFriendPickerViewController cacheDescriptor];
[cacheDescriptor prefetchAndCacheForSession:session];
}
break;
case FBSessionStateClosed: {
[self StopSpinner];
UIViewController *topViewController = [self.navigationController topViewController];
UIViewController *modalViewController = [topViewController modalViewController];
if (modalViewController != nil) {
[topViewController dismissViewControllerAnimated:YES completion:nil];
}
//[self.navigationController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
case FBSessionStateClosedLoginFailed: {
[self StopSpinner];
[self performSelector:#selector(showLoginView) withObject:nil afterDelay:0.5f];
}
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:SCSessionStateChangedNotificationFL object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:[NSString stringWithFormat:#"Error: %#", [FacebookFriendsListViewController FBErrorCodeDescription:error.code]] message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[alertView release];
}
}
see my accepted this answer on How to get the list of friend without opening FBFriendPickerViewController iOS

Post to Facebook not working from delegate

I have added FBSdk in my project along with SBJson classes, what files should i import in my second view controller to work my code ?
I want to post on Fb using the description under url so for that i need to include this code into my second view controller, but i am stuck in a part i founded that the below code should be added in the second view controller but the "delegate:self" not works, as i am doing this first time so can any one guide me how should i code in my second view controller keeping into account the values from the app delegate (How should i get the values from the app delegate of FB to the second view so that i can add this code in second code plz can any one correct this code)
facebook = [[Facebook alloc] initWithAppId:#"YOUR_APP_ID"];
// how should i take this id from the app delegate ?
NSArray* permissions = [NSArray arrayWithObjects:#"read_stream",
#"publish_stream", nil];
[facebook authorize:permissions delegate:self];
NSMutableDictionary* params = [[NSMutableDictionary alloc]
initWithCapacity:1]
[params setObject:#"Testing" forKey:#"name"];
[params setObject:#"IMAGE_URL" forKey:#"picture"];
[params setObject:#"Description" forKey:#"description"];
[facebook requestWithGraphPath:#"me/feed"
andParams:params
andHttpMethod:#"POST"
andDelegate:self];
Is the above code correct ?
How should i implement it in my second view controller in -(void)fb_share (method).
My App Delegate File is Like this :
#import "AppDelegate.h"
#import "ViewController.h"
#import "ServerRequests.h"
#import "DBManager.h"
#import "SBJson.h"
#include "FBSession.h"
#import "FBRequest.h"
#import "FBGraphUser.h"
NSString *const FBSessionStateChangedNotification = #"com.myapp:FBSessionStateChangedNotification";
#implementation AppDelegate
#synthesize userId;
#synthesize dbSnyced;
#synthesize fbId;
#synthesize loginView;
- (void)dealloc
{
[_window release];
[_viewController release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{ self.fbId = #"-1";
self.dbSnyced = NO;
self.loginView = nil;
self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];
self.viewController = [[[ViewController alloc] initWithNibName:#"ViewController" bundle:nil] autorelease];
self.navigationController = [[[UINavigationController alloc] initWithRootViewController:self.viewController] autorelease];
self.window.rootViewController = self.navigationController;
[self.window makeKeyAndVisible];
if (![self openSessionWithAllowLoginUI:NO]) {
[self showLogin:NO];
}
return YES;
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[self checkAccountLogin];
}
- (void) applicationDidEnterBackground:(UIApplication *)application
{
[self hideLogin:NO];
}
- (void) applicationWillTerminate:(UIApplication *)application
{
NSLog(#"applicationWillTerminate");
[self hideLogin:NO];
[FBSession.activeSession close];
}
- (void) checkAccountLogin
{
self.dbSnyced = NO;
if([ServerRequests serverIsReachableAlertIfNo:YES]) {
DBManager *db = [[[DBManager alloc] initWithPath:DB_NAME] autorelease];
NSDictionary *userDic = [[db smartQueryForArrayWithStatement:#"SELECT * FROM table WHERE id=1"] objectAtIndex:0];
NSString *loginType = [userDic objectForKey:#"login_type"];
if([loginType isEqualToString:#"none"]) {
NSLog(#"no login type");
[self showLogin:NO];
}
else {
self.userId = [[userDic objectForKey:#"user_id"] intValue];
if([loginType isEqualToString:#"Facebook"]) {
NSLog(#"Facebook account");
[FBSession.activeSession handleDidBecomeActive];
}
else if([loginType isEqualToString:#"MyApp"]) {
NSLog(#"MyApp account");
}
}
}
}
#pragma - Fb stuff
/*
* Callback for session changes.
*/
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState) state error:(NSError *)error
{
NSLog(#"sessionStateChanged");
switch (state) {
case FBSessionStateOpen:
if (!error) {
[self handleFbUserDetails];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
[[NSNotificationCenter defaultCenter] postNotificationName:FBSessionStateChangedNotification object:session];
if (error) {
NSLog(#"error: %#", error.localizedDescription);
if(self.loginView) {
[self.loginView hideLoading];
}
}
}
/*
* Opens a Facebook session and optionally shows the login UX.
*/
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
return [FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
/*
* If we have a valid session at the time of openURL call, we handle
* Facebook transitions by passing the url argument to handleOpenURL
*/
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
// attempt to extract a token from the url
return [FBSession.activeSession handleOpenURL:url];
}
- (BOOL) activeFBSession
{
return FBSession.activeSession.isOpen;
}
- (void) closeFBSession
{
NSLog(#"closeFBSession");
[FBSession.activeSession closeAndClearTokenInformation];
}
- (void) showLogin:(BOOL)animated
{
if(!self.loginView) {
self.loginView = [[[LoginViewController alloc] init] autorelease];
[[self.navigationController topViewController] presentViewController:self.loginView animated:animated completion:nil];
}
}
- (void) hideLogin:(BOOL)animated
{
if(self.loginView) {
[self.viewController gotToTab:0];
[self.loginView hideLoading];
[[self.navigationController topViewController] dismissViewControllerAnimated:animated completion:^{
self.loginView = nil;
NSLog(#"self.loginView = nil");
}];
}
}
- (void) handleFbUserDetails
{
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
NSLog(#"fb connected");
self.fbId = [user objectForKey:#"id"];
self.userId = -1;
ASIFormDataRequest *request = [ServerRequests ASIFormDataRequestForSrcipt:#"facebookUser"];
[request setPostValue:[user objectForKey:#"id"] forKey:#"fbId"];
[request setPostValue:user.first_name forKey:#"first_name"];
[request setPostValue:user.last_name forKey:#"last_name"];
[request setPostValue:user.location.name forKey:#"location"];
[request setCompletionBlock:^{
NSString *response = [request responseString];
NSLog(#"facebookUser response: %#", response);
if([response rangeOfString:#"ERROR"].location == NSNotFound) {
self.userId = [response intValue];
DBManager *db = [[DBManager alloc] initWithPath:DB_NAME];
NSString *q = [NSString stringWithFormat:#"UPDATE table SET login_type = 'Facebook', user_id = '%#' WHERE id = 1", response];
NSLog(#"%#", q);
[db executeStatement:q];
[db release];
}
else {
}
[self sessionBecameActive];
}];
[request startAsynchronous];
[self hideLogin:YES];
}
else {
NSLog(#"error: %#", error.localizedDescription);
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Facebook Request Error" message:#"Cannot connect to Facebook." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
alert.delegate = self;
[alert show];
[alert release];
if(self.loginView) {
[self.loginView hideLoading];
}
}
[ServerRequests SyncDataBase];
}];
}
- (void) signOut
{
[self closeFBSession];
DBManager *db = [[DBManager alloc] initWithPath:DB_NAME];
[db executeStatement:#"UPDATE table SET login_type = 'none' WHERE id = 1"];
[db release];
[self showLogin:YES];
}
- (void) sessionBecameActive
{
[self.viewController sessionBecameActive];
}
#end
Can any one figure out what code should i write in the -(void)fb_share method in second view controller by getting values from the delegate ?
Any Help !
I did this ... and getting Error: HTTP status code: 400 ... but the user name get's displayed on alert
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
// NSArray* permissions = [NSArray arrayWithObjects:#"read_stream",
// #"publish_stream", nil];
// [facebook authorize:permissions delegate:self];
self.params = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
#"https://developers.facebook.com/ios", #"link",
#"https://developers.facebook.com/attachment/iossdk_logo.png", #"picture",
#"Facebook SDK for iOS", #"name",
#"Build great social apps and get more installs.", #"caption",
#"The Facebook SDK for iOS makes it easier and faster to develop Facebook integrated iOS apps.", #"description",
nil];
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Upload to FB?"
message:[NSString stringWithFormat:#"Upload to ""%#"" Account?", user.name]
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"No",#"Yes", nil];
[FBRequestConnection startWithGraphPath:#"me/feed"
parameters:self.params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
UIAlertView *tmp = [[UIAlertView alloc]
initWithTitle:#"Success"
message:#"PostUploaded"
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Ok", nil];
[tmp show];
[tmp release];
}
}];
[tmp show];
[tmp release];
}
}];
.. what should i do now ?
declare facebook as a property in .h file of your appDelegate
then in second view controller import AppDelegate
in .m file where you want the Facebook object
get it like
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
Facebook *facebook = appDelegate.facebook;

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

Facebook iOS SDK not returning user email

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

problem submitting tweet to twitter from iphone

MGTwitterEngine.m
- (NSString *)username
{
return [[_username retain] autorelease];
}
- (NSString *)password
{
return [[_password retain] autorelease];
}
- (void)setUsername:(NSString *)newUsername password:(NSString *)newPassword
{
// Set new credentials.
[_username release];
_username = [newUsername retain];
[_password release];
_password = [newPassword retain];
if ([self clearsCookies]) {
// Remove all cookies for twitter, to ensure next connection uses new credentials.
NSString *urlString = [NSString stringWithFormat:#"%#://%#",
(_secureConnection) ? #"https" : #"http",
_APIDomain];
NSURL *url = [NSURL URLWithString:urlString];
NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSEnumerator *enumerator = [[cookieStorage cookiesForURL:url] objectEnumerator];
NSHTTPCookie *cookie = nil;
while (cookie == [enumerator nextObject]) {
[cookieStorage deleteCookie:cookie];
}
}
}
- (NSString *)sendUpdate:(NSString *)status
{
return [self sendUpdate:status inReplyTo:0];
}
- (NSString *)sendUpdate:(NSString *)status inReplyTo:(unsigned long)updateID
{
if (!status) {
return nil;
}
NSString *path = [NSString stringWithFormat:#"statuses/update.%#", API_FORMAT];
NSString *trimmedText = status;
if ([trimmedText length] > MAX_MESSAGE_LENGTH) {
trimmedText = [trimmedText substringToIndex:MAX_MESSAGE_LENGTH];
}
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithCapacity:0];
[params setObject:trimmedText forKey:#"status"];
if (updateID > 0) {
[params setObject:[NSString stringWithFormat:#"%u", updateID] forKey:#"in_reply_to_status_id"];
}
NSString *body = [self _queryStringWithBase:nil parameters:params prefixed:NO];
return [self _sendRequestWithMethod:HTTP_POST_METHOD path:path
queryParameters:params body:body
requestType:MGTwitterUpdateSendRequest
responseType:MGTwitterStatus];
}
TwitterPostViewController.m
- (IBAction)submitTweet{
[tweet resignFirstResponder];
if([[tweet text] length] > 0){
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] valueForKey:#"TwitterUsername"]);
NSLog(#"%#",[[NSUserDefaults standardUserDefaults] valueForKey:#"TwitterPassword"]);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
[engine sendUpdate:[tweet text]];
}
}
- (void)requestFailed:(NSString *)requestIdentifier withError:(NSError *)error{
NSLog(#"Fail: %#", error);
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
UIAlertView *failAlert;
if([error code] == 401){
failAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Incorrect Username & Password." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[failAlert setTag:10];
[failAlert setDelegate:self];
}
else
{
failAlert = [[UIAlertView alloc] initWithTitle:#"Error" message:#"Failed sending status to Twitter." delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
}
[failAlert show];
[failAlert release];
}
It shows me the fail popup of Incorrect username and password
I have checked through nslog that username and password are going correct.
what could be wrong?
It looks like the version of MGTwitterEngine you're using is trying to use basic auth. That was switched off in Twitter in favour of OAuth. Get a newer version of MGTwitterEngine (or a fork that supports OAuth).