Getting user data from facebook login in xcode? - iphone

I have integrated facebook login in my app.But Im unable to get user data ie it is not entering the user details loop
In Appdelegate.m
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"email",
#"user_likes",
nil];
return [FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
if (!error) {
// We have a valid session
NSLog(#"User session found");
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *error) {
if (!error) {
NSLog(#"%#",user);
}}];
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[[FBSession activeSession] closeAndClearTokenInformation];
break;
default:
break;
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
}
But I dont find NSLog of user NSLog(#"%#",user) to be printed eventhough the session is opened bcoz NSLog(#"User session found") is printed
Y is it so ?

I had same issue where I was not able to enter in the block once came back after log in after an hour I figured out that I was returning mysession class instead of instance of mysession. This might fix your issue:
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [mysession handleOpenURL:url];
}

Related

FB integration in ios app issues

I have integrated the facebook in my ios app and it is working nice.
But when i stored my FB credentials in setting it is not working.
It goes in following state
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
NSLog(#"case open session");
// if([sharePref returnFbName].length==0)
[self listFriendsFB];
break;
case FBSessionStateClosed:
NSLog(#"case FBSessionStateClosed session");
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// be looking at the root view.
//[viewController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
NSLog(#"case close or fail session");
break;
default:
break;
}
It goes in FBSessionStateClosedLoginFailed , and error occurs.
And if I delete my account from phone setting it working fine i.e the session opens and it is logged in correctly.
Here is my code
- (void)openSession
{
//[self syncFacebookAccount];
NSArray *permissions=[[NSArray alloc]initWithObjects:#"email,publish_actions",nil];
dispatch_async(dispatch_get_main_queue(), ^{
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
NSLog(#"fb open session");
[self sessionStateChanged:session state:state error:error];
}];
});
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
NSLog(#"case open session");
// if([sharePref returnFbName].length==0)
[self fourthViewInitialization];
[self getFacebookInfo];
break;
case FBSessionStateClosed:
NSLog(#"case FBSessionStateClosed session");
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// be looking at the root view.
//[viewController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
NSLog(#"case close or fail session");
break;
default:
break;
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:AlertTitle
message:#"We are currently facing facebook connectivity issues. Please try again later!"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
NSLog(#"error facebook : %#",error);
[alertView show];
[self hideActivityIndicator];
}
}
#pragma facebook methods
-(void)getFacebookInfo
{
// [NSThread detachNewThreadSelector:#selector(startLoader) toTarget:self withObject:nil];
NSString *query =[NSString stringWithFormat:#"Select name,uid,pic_square from user where uid=me()"];
// Set up the query parameter
my_info=[[NSMutableDictionary alloc]init];
my_info_array=[[NSMutableArray alloc ]init];
NSDictionary *queryParam =
[NSDictionary dictionaryWithObjectsAndKeys:query, #"q", nil];
// Make the API request that uses FQL
[FBRequestConnection startWithGraphPath:#"/fql"
parameters:queryParam
HTTPMethod:#"GET"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (error) {
NSLog(#"Error: %#", [error localizedDescription]);
[self hideActivityIndicator];
} else {
// NSLog(#"Result: %#", result);
// [self hideActivityIndicator];
my_info_array=(NSMutableArray *)[result objectForKey:#"data"];
my_info=[my_info_array objectAtIndex:0];
//NSLog(#"my info array %#",my_info_array);
NSLog(#"my info from fb %#",my_info);
//return my_info;
[firstView removeFromSuperview];
[self.view addSubview:fourthView];
displayNameLabel.text=[NSString stringWithFormat:#"%#%#",displayNameLabel.text,[my_info objectForKey:#"name"]];
[registerRequest setObject:[my_info objectForKey:#"name"] forKey:#"displayName"];
//[registerRequest setObject:[my_info objectForKey:#"email"] forKey:#"emailId"];
[registerRequest setObject:[my_info objectForKey:#"uid"] forKey:#"uid"];
[SharedPreferenceClass setFBUID:[my_info objectForKey:#"uid"]];// 30 sept
[registerRequest setObject:[my_info objectForKey:#"pic_square"] forKey:#"profilePic"];
NSString* picPath = [my_info objectForKey:#"pic_square"];
if (picPath.length>0) {
[SharedPreferenceClass setUserProfilePictureDefault:picPath];
}else{
[SharedPreferenceClass setUserProfilePictureDefault:#""];
}
//displayName.text=[my_info objectForKey:#"name"];
[self hideActivityIndicator];
}
}];
}
Thanks in advance.
I used this to open session when FB credentials are available in phone settings
// Initialize a session object
FBSession *session = [[FBSession alloc] init];
// Set the active session
[FBSession setActiveSession:session];
[session openWithBehavior:FBSessionLoginBehaviorWithFallbackToWebView
completionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
// Respond to session state changes,
NSLog(#"fb open session %#",error);
[self sessionStateChanged:session state:status error:error];
}];
And once session is opened I have used following code to get FB friends data.
NSArray *permissions=[[NSArray alloc]initWithObjects:#"email,publish_actions",nil];
dispatch_async(dispatch_get_main_queue(), ^{
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
NSLog(#"fb open session");
[self sessionStateChanged:session state:state error:error];
}];
});

Facebook SDK login issue on iPhone

I am trying to integrate the Facebook SDK into my application, and it works in my simulator perfectly. When I install it onto my iPhone and try running it, it shows me an alert, which states, "myapp needs to access your profile, friendlist, etc", and when I choose to allow it nothing happens - and it requires these permissions.
I have installed the Facebook application on my iPhone, tried logging out and back in many times, but without use.
But, when I go to settings and delete the Facebook details, it works perfectly:
How can I fix this?
I used following way its working for me :
-(void)openFacebookAuthentication
{
NSArray *permission = [NSArray arrayWithObjects:kFBEmailPermission,kFBUserPhotosPermission, nil];
FBSession *session = [[FBSession alloc] initWithPermissions:permission];
[FBSession setActiveSession: [[FBSession alloc] initWithPermissions:permission] ];
[[FBSession activeSession] openWithBehavior:FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
switch (status) {
case FBSessionStateOpen:
[self getMyData];
break;
case FBSessionStateClosedLoginFailed: {
// prefer to keep decls near to their use
// unpack the error code and reason in order to compute cancel bool
NSString *errorCode = [[error userInfo] objectForKey:FBErrorLoginFailedOriginalErrorCode];
NSString *errorReason = [[error userInfo] objectForKey:FBErrorLoginFailedReason];
BOOL userDidCancel = !errorCode && (!errorReason || [errorReason isEqualToString:FBErrorLoginFailedReasonInlineCancelledValue]);
if(error.code == 2 && ![errorReason isEqualToString:#"com.facebook.sdk:UserLoginCancelled"]) {
UIAlertView *errorMessage = [[UIAlertView alloc] initWithTitle:kFBAlertTitle
message:kFBAuthenticationErrorMessage
delegate:nil
cancelButtonTitle:kOk
otherButtonTitles:nil];
[errorMessage performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:YES];
errorMessage = nil;
}
}
break;
// presently extension, log-out and invalidation are being implemented in the Facebook class
default:
break; // so we do nothing in response to those state transitions
}
}];
permission = nil;
}
Remember to add your app to facebook developers/apps!!
If not, you can't interact with their servers...
Ok, I know what is going wrong. let me know that whatever you are doing is right but the result that you want will require something else.
Try this -
First of all implement all the facebook sdk delegate methods in your app delegate.
- (IBAction)loginWithFacebookButtonTapped:(id)sender
{
IntubeAppDelegate *delegat = (IntubeAppDelegate*)[[UIApplication sharedApplication] delegate];
[delegat doLoginAndSwitch];
}
Now, in your appDelegate -
-(void) doLoginAndSwitch
{
[self openSessionWithAllowLoginUI:YES];
}
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI
{
NSArray *permissions = [NSArray arrayWithObjects:#"email", nil];
return [FBSession openActiveSessionWithPublishPermissions:permissions
defaultAudience:FBSessionDefaultAudienceFriends
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
-(BOOL)openSessionWithAllowPublishStreamPermission:(BOOL)allowLoginUI
{
NSArray *permissions = [NSArray arrayWithObjects:#"publish_actions",#"publish_stream", nil];
[[FBSession activeSession] requestNewPublishPermissions:permissions defaultAudience:FBSessionDefaultAudienceEveryone completionHandler:^(FBSession *session, NSError *error){
}];
return YES;
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState)state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:
if(!error)
{
// NSLog(#"FBSessionStateOpen :- logged in");
[self openSessionWithAllowPublishStreamPermission:YES];
// Your code
}
}
}
Also to switch back to your application -
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
I hope you would get what you desire now. :)

Fetching user details from Facebook in iOS

I'm new to iPhone development. I'm doing an App where the user has 2 login through Facebook, once he submits his credentials and clicks on Sign In button, I have to fetch details like First name, email and gender from Facebook and after fetching the user has to be directed to the Registration page of the app with the details filled and i need this app to be compatible for iPhone 4,4s and 5.
I tried doing this using the Facebook Graph API but couldn't get it, so anyone can help me out.
Thanks in Advance.
You can do this by using following code :
[FBSession openActiveSessionWithReadPermissions:#[#"email",#"user_location",#"user_birthday",#"user_hometown"]
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
switch (state) {
case FBSessionStateOpen:
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (error) {
NSLog(#"error:%#",error);
}
else
{
// retrive user's details at here as shown below
NSLog(#"FB user first name:%#",user.first_name);
NSLog(#"FB user last name:%#",user.last_name);
NSLog(#"FB user birthday:%#",user.birthday);
NSLog(#"FB user location:%#",user.location);
NSLog(#"FB user username:%#",user.username);
NSLog(#"FB user gender:%#",[user objectForKey:#"gender"]);
NSLog(#"email id:%#",[user objectForKey:#"email"]);
NSLog(#"location:%#", [NSString stringWithFormat:#"Location: %#\n\n",
user.location[#"name"]]);
}
}];
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
} ];
and don't forgot to import FacebookSDK/FacebookSDK.h in your code.
EDIT : Update for Facebook SDK v4 (23 April,2015)
Now, Faceboook have released new SDK with major changes. In which FBSession class is deprecated. So all users are suggested to migrate to new sdk and APIs.
Below I have mentioned, how we can get user details via Facebook SDK v4 :
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#”fetched user:%#”, result);
}
}];
}
But before fetching user details, we have to integrate new Facebook login in our code as described in Documentation here.
Here is the Changelog for SDK v4. I suggest going through it for being updated.
Add info.plist file:
- (IBAction)btn_fb:(id)sender
{
if (!FBSession.activeSession.isOpen)
{
NSArray *_fbPermissions = #[#"email",#"publish_actions",#"public_profile",#"user_hometown",#"user_birthday",#"user_about_me",#"user_friends",#"user_photos",];
[FBSession openActiveSessionWithReadPermissions:_fbPermissions allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState state, NSError *error)
{
if (error)
{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Error" message:error.localizedDescription delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
}
else if(session.isOpen)
{
[self btn_fb:sender];
}
}];
return;
}
[FBRequestConnection startWithGraphPath:#"me" parameters:[NSDictionary dictionaryWithObject:#"cover,picture.type(large),id,name,first_name,last_name,gender,birthday,email,location,hometown,bio,photos" forKey:#"fields"] HTTPMethod:#"GET" completionHandler:^(FBRequestConnection *connection, id result, NSError *error)
{
{
if (!error)
{
if ([result isKindOfClass:[NSDictionary class]])
{
NSLog(#"%#",result);
}
}
}
}];
}
Please refer these following links, sothat you can get some idea.
https://www.parse.com/tutorials/integrating-facebook-in-ios
Facebook iOS 6 - get user info
get Facebook user profile data after getting access token in iOS 5
Display a user's profile name and image through the Facebook instance for iOS
How to cache Facebook User Info with Facebook Login in IOS App
How do I get the full User object using Facebook Graph API and facebook ios sdk?
Hope it will helps you....
Use the FBConnect API for fetch user information.its easy to use
Fbconnect API
Hope it Works For you :)
you have to use graph path to get user Information.
-(void)getEmailId
{
[facebook requestWithGraphPath:#"me" andDelegate:self];
}
- (void)openSession
{
if (internetActive) {
NSArray *permissions=[NSArray arrayWithObjects:#"read_stream",#"email",nil];
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}else
{
UIAlertView *alert=[[UIAlertView alloc] initWithTitle:#"" message:#"Internet Not Connected" delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alert show];
}
}
#pragma mark- request delegate methods
- (void)request:(FBRequest *)request didLoad:(id)result
{
NSLog(#"request did load successfully....");
// __block NSDictionary *dictionary=[[NSDictionary alloc] init];
if ([result isKindOfClass:[NSDictionary class]]) {
NSDictionary* json = result;
NSLog(#"email id is %#",[json valueForKey:#"email"]);
NSLog(#"json is %#",json);
[[NSUserDefaults standardUserDefaults] setValue:[json valueForKey:#"email"] forKey:#"fbemail"];
[self.viewController login:YES];
}
}
- (void)request:(FBRequest *)request didFailWithError:(NSError *)error
{
UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:#"" message:#"Server not responding.." delegate:nil cancelButtonTitle:#"Ok" otherButtonTitles:nil];
[alertView show];
[self fblogout];
[self showLoginView];
NSLog(#"request did fail with error");
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen: {
//state open action
}
// Initiate a Facebook instance
facebook = [[Facebook alloc]
initWithAppId:FBSession.activeSession.appID
andDelegate:nil];
// Store the Facebook session information
facebook.accessToken = FBSession.activeSession.accessToken;
facebook.expirationDate = FBSession.activeSession.expirationDate;
if (![[NSUserDefaults standardUserDefaults] valueForKey:#"fbemail"]) {
[MBProgressHUD showHUDAddedTo:self.viewController.view animated:YES];
[self getEmailId];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// be looking at the root view.
[self.navController popToRootViewControllerAnimated:NO];
[FBSession.activeSession closeAndClearTokenInformation];
facebook = nil;
[self showLoginView];
break;
default:
break;
}
[[NSNotificationCenter defaultCenter]
postNotificationName:FBSessionStateChangedNotification
object:session];
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
FBRequest *request = [FBRequest requestForMe];
[request startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error) {
// handle successful response
} else if ([error.userInfo[FBErrorParsedJSONResponseKey][#"body"][#"error"][#"type"] isEqualToString:#"OAuthException"]) { // Since the request failed, we can check if it was due to an invalid session
NSLog(#"The facebook session was invalidated");
[self logoutButtonTouchHandler:nil];
} else {
NSLog(#"Some other error: %#", error);
}
}];
Facebook has currently updated their SDK version to 4.x. To Fetch user's profile information you will need to explicitly call graph API after login success (ask for required permissions).
FBSDKGraphRequest *request = [[FBSDKGraphRequest alloc]
initWithGraphPath:#"/me"
parameters:#{ #"fields": #"id,name,email"}
HTTPMethod:#"GET"];
[request startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
// Insert your code here
}];

How to get session login information to my UIWebView by FacebookSDK

After logging in to facebook with FacebookSDK, and I want to display a page using a UIWebView.
It is displayed correctly when I login for the first time.
But I close and restart the app, Even though the facebook session still open, I can't get login session to my UIWebView.
Do you have any suggestions for that, when I re-run the app, to get as it is the Facebook session information?
This is my code example.
#interface FBLogin2ViewController ()
#end
#implementation FBLogin2ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
// To-do, show logged in view
NSString *appID = [FBSession defaultAppID];
NSLog(#"Session token exists %#", appID);
}
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
- (IBAction)onLogin:(id)sender {
NSArray *permissions = nil;
if (![FBSession activeSession]) {
FBSession *session = [[FBSession alloc] initWithAppID:#"000000000000" permissions:permissions defaultAudience:FBSessionDefaultAudienceEveryone urlSchemeSuffix:#"fb" tokenCacheStrategy:nil];
[FBSession setActiveSession:session];
}
else if( [FBSession activeSession].isOpen )
{
[[FBSession activeSession] closeAndClearTokenInformation];
FBSession.activeSession = nil;
}
[[FBSession activeSession] openWithBehavior:FBSessionLoginBehaviorForcingWebView
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
- (IBAction)onLogout:(id)sender {
[FBSession.activeSession closeAndClearTokenInformation];
FBSession.activeSession = nil;
}
- (IBAction)onGoWeb:(id)sender {
NSURL *url = [NSURL URLWithString:#"http://www.facebook.com/xxxxx?fref=xx"];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[_webView loadRequest:request];
_webView.delegate = self;
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen: {
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// be looking at the root view.
break;
default:
break;
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:error.localizedDescription
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
}
}
#end
1)call openFBSessionIfAvaliable in didFinishLaunchingWithOptions method
//in appdelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
[self openFBSessionIfAvaliable];
}
//in appdelegate
- (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];
}
//in appdelegate
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
[[FBSession activeSession] handleDidBecomeActive];
}
//in appdelegate
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
[[FBSession activeSession] close];
}
-(void)openFBSessionIfAvaliable
{
[FBSession setActiveSession:[FBSession new]];
if ([FBSession activeSession].state == FBSessionStateCreatedTokenLoaded)
{
[self openFBSessionWithAllowLoginUI:NO];
}
}
- (BOOL)openFBSessionWithAllowLoginUI:(BOOL)allowLoginUI
{
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"email",nil];
return [FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error)
{
[self sessionStateChanged:session
state:state
error:error];
}];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state)
{
case FBSessionStateOpen:
if (!error)
{
NSString *_facebookToken = [[FBSession activeSession] accessToken];
NSString *_facebookEmail = [user objectForKey:#"email"];
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
if (error)
{
[FBSession.activeSession closeAndClearTokenInformation];
/*UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:#"Please try Again"
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];*/
}
}
2) On button Click of "Login via facebook" call below method
[self openFBSessionWithAllowLoginUI:YES];
3) Now every time when you launch the app, it will check the Facebook session, if found then proceed further otherwise show the button "Login via Facebook".session
I hope it will solve your problem.

Facebook SDK error 3 and error 2

I have this application I am using for posting on facebook and I am currently facing difficulties in posting on some of the iOS 6.0 devices. I am using facebook SDK 3.1 only and trying to publish action. Following is the code I am using in the class to initiate the read permission.
For the access I am using the following code.
// CALLING THIS CODE BLOCK IN ONE BUTTON ACTION.
if (FBSession.activeSession.isOpen)
{
[self pickaChoice];
}
else
{
[FBSession openActiveSessionWithPublishPermissions:[NSArray arrayWithObjects:#"publish_actions", nil]
defaultAudience:FBSessionDefaultAudienceEveryone
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state)
{
case FBSessionStateOpen:
[FBSession setActiveSession:session];
[self pickaChoice];
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
// Once the user has logged in, we want them to
// ...
[FBSession.activeSession closeAndClearTokenInformation];
break;
default:
break;
}
if (error) {
NSString* message = [NSString stringWithFormat:#"You have disallowed application to post on your behalf."];
UIAlertView *alertView = [[UIAlertView alloc]
initWithTitle:#"Error"
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil];
[alertView show];
[FBSession.activeSession closeAndClearTokenInformation];
}
}
-(void)pickaChoice
{
/* Just a class to select message and then retrieve the message in the next function
-(void)didSelectaPhraseToPost:(NSString *)message */
FBPublishViewController *fbPublishViewController = [[FBPublishViewController alloc] initWithNibName:#"FBPublishViewController"
bundle:[NSBundle mainBundle]];
fbPublishViewController.selectionDelegate = self;
[self presentViewController:fbPublishViewController
animated:YES
completion:^(){
//nil
}];
}
-(void)didSelectaPhraseToPost:(NSString *)message
{
// Selecting a message from a class and retrieving here. This is the message to post on the feed.
[self publishMessage:message];
}
- (void) performPublishAction:(void (^)(void)) action
{
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
[FBSession.activeSession reauthorizeWithPublishPermissions:[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
action();
}
//For this example, ignore errors (such as if user cancels).
}];
} else {
action();
}
}
- (void)publishMessage:(NSString *)message
{
NSMutableDictionary *params = [NSMutableDictionary dictionaryWithObjectsAndKeys:
#"APP_NAME", #"name",
message, #"message",
APP_LINK, #"link",
#"APP_PICTURE", #"picture",
nil];
[self.spinner startAnimating];
[self performPublishAction:^{
[FBRequestConnection
startWithGraphPath:#"me/feed"
parameters:params
HTTPMethod:#"POST"
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
[self.spinner stopAnimating];
NSString *messageTitle = nil;
NSString *message = nil;
// If the result came back okay with no errors...
if (result && !error)
{
NSLog(#"accessToken : %#",[FBSession activeSession].accessToken );
NSLog(#"result : %#",result);
messageTitle = #"Success";
message = #"App has posted to facebook";
}else{
NSLog(#"error : %#",error);
messageTitle = #"Error v1.1";
//message = error.localizedDescription;
message = #"Unable to process the request. Please check the permissions for the application.";
[FBSession.activeSession closeAndClearTokenInformation];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:messageTitle
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles: nil];
[alert show];
//TODO maybe clear connection here if we want to force an new login
}];
}];
}
Now the problem is on some iOS 6.0 devices it is throwing facebook.sdk.error 3 and on some devices it is throwing facebook.sdk.error 2 even when the application is permitted to post. In the current code I have just changed the message to a custom for more user friendly message but if you go on to print the localizedDescription it will show those.
On most of the iOS 6.0 devices the code is working absolutely fine and the message is posted. Let me know if anyone can find out where the problem exactly is. I have spent like days now in this and still not getting where the problem is.
Edit 1
A pattern I observed that when facebook application is installed and user is logged in through it and not logged in through the native settings I am facing these sort of difficulties.
It would be good if you find out your iOS version and use apple's default facebook shar view for iOS 6.0 and on another side for below version you must need to use Graph API.
I used this method its work for me fine in iOS6, may be its help you.
-(void)openFacebookAuthentication
{
NSArray *permission = [NSArray arrayWithObjects:kFBEmailPermission,kFBUserPhotosPermission, nil];
[FBSession setActiveSession: [[FBSession alloc] initWithPermissions:permission] ];
[[FBSession activeSession] openWithBehavior:FBSessionLoginBehaviorForcingWebView completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
switch (status) {
case FBSessionStateOpen:
[self getMyData];
break;
case FBSessionStateClosedLoginFailed: {
NSString *errorCode = [[error userInfo] objectForKey:FBErrorLoginFailedOriginalErrorCode];
NSString *errorReason = [[error userInfo] objectForKey:FBErrorLoginFailedReason];
BOOL userDidCancel = !errorCode && (!errorReason || [errorReason isEqualToString:FBErrorLoginFailedReasonInlineCancelledValue]);
if(error.code == 2 && ![errorReason isEqualToString:#"com.facebook.sdk:UserLoginCancelled"]) {
UIAlertView *errorMessage = [[UIAlertView alloc] initWithTitle:kFBAlertTitle
message:kFBAuthenticationErrorMessage
delegate:nil
cancelButtonTitle:kOk
otherButtonTitles:nil];
[errorMessage performSelectorOnMainThread:#selector(show) withObject:nil waitUntilDone:YES];
errorMessage = nil;
}
}
break;
// presently extension, log-out and invalidation are being implemented in the Facebook class
default:
break; // so we do nothing in response to those state transitions
}
}];
permission = nil;
}