Facebook App Login: Is it possible to catch 'cancelButtonPressed' event? - event-handling

Is it possible to catch event 'CancelButtonPressed' in Facebook App through facebook-ios-sdk authorization flow?
I use pretty old version of Facebook SDK for IOS and open session like this:
[_facebookSession openWithBehavior:FBSessionLoginBehaviorWithNoFallbackToWebView
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
NSLog(#"this is FBSession State: %d",status);
NSLog(#"this is NSError: %#",error);
NSLog(#"create new session with permissions: %#",_facebookSession.permissions);
}];
I saw this question, but maybe something changed in Facebook IOS SDK?
Maybe somebody knows answer or good solution?
Thanks for help!
EDIT:
if ([_facebookSession state]==FBSessionStateCreatedOpening){
// if we call FBApp, facebook session will be in this state (createdOpening)
// and we need to check it and close, to recall FBApp
[_facebookSession closeAndClearTokenInformation];
// and now recrate session and open it ;)
_facebookSession = [[FBSession alloc] initWithAppID:kAppId
permissions:permissions
urlSchemeSuffix:nil
tokenCacheStrategy:[FBSessionTokenCachingStrategy defaultInstance]
];
//and reopen it like `[_facebookSession openWith... ];`
}

Related

The operation couldn't be completed.(com.facebook.sdk error 2.) error iOS 6 [duplicate]

I'm using die Facebook SDK 3.1.1 to implement FB Connect in my iOS application. This works fine in the simple case with either the new FB integration (logged in on iOS) or falling back to the normal authorization via web view (I do not have the native Facebook application installed in both cases).
The problem occurs when I switch the account on iOS level. Logging out and logging in with a different FB user account.
To log in/authorize I perform:
[FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
If then get a FBSessionStateClosedLoginFailed every time even though I perform a closeAndClearTokenInformation when that state is reached:
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
NSLog(#"Session State Changed: %u", [[FBSession activeSession] state]);
switch (state) {
case FBSessionStateOpen:
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
NSLog(#"FBSessionStateClosedLoginFailed ERROR: %#", [error description]);
[[FBSession activeSession] closeAndClearTokenInformation];
break;
default:
break;
}
However, I receive the same state on every retry. My log says the following:
FBSDKLog: FBSession **INVALID** transition from FBSessionStateCreated to FBSessionStateClosed
FBSDKLog: FBSession transition from FBSessionStateCreated to FBSessionStateCreatedOpening
FBSDKLog: FBSession transition from FBSessionStateCreatedOpening to FBSessionStateClosedLoginFailed Session State Changed: 257
FBSessionStateClosedLoginFailed TOKEN: (null)
FBSessionStateClosedLoginFailed ERROR: Error Domain=com.facebook.sdk Code=2 "The operation couldn’t be completed. (com.facebook.sdk error 2.)" UserInfo=0xb24cc20 {com.facebook.sdk:ErrorLoginFailedReason=com.facebook.sdk:ErrorLoginFailedReason}
Can anyone reproduce this or has any idea where the problem might lie?
Another answer gives a way to manually resync the device with the server. I defined a method called fbRsync to call this code. Make sure to #import <Accounts/Accounts.h> in your implementation file and then define this method:
-(void)fbResync
{
ACAccountStore *accountStore;
ACAccountType *accountTypeFB;
if ((accountStore = [[ACAccountStore alloc] init]) && (accountTypeFB = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook] ) ){
NSArray *fbAccounts = [accountStore accountsWithAccountType:accountTypeFB];
id account;
if (fbAccounts && [fbAccounts count] > 0 && (account = [fbAccounts objectAtIndex:0])){
[accountStore renewCredentialsForAccount:account completion:^(ACAccountCredentialRenewResult renewResult, NSError *error) {
//we don't actually need to inspect renewResult or error.
if (error){
}
}];
}
}
I then call fbResync if openActiveSessionWithReadPermissions yields an error:
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
if(error)
{
NSLog(#"Session error");
[self fbResync];
[NSThread sleepForTimeInterval:0.5]; //half a second
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
else
[self sessionStateChanged:session state:state error:error];
}];
The half a second delay is likely unnecessary, but it currently gives me piece of mind.
This seems to solve the problem for me. I can now switch between Facebook accounts and am able to log in. Yay!
I had the same problem. Check that your FB App is enabled in Settings -> Facebook.
Mine was disabled (even though I don't remember disabling it) and once I enabled it, it was fixed.
In my test process, I've added and removed my FB App several times from my FB Account, which is linked with my iPhone. It may explain why, magically, my app was disabled.
In ios 6 with fb sdk 3.1.1. Please pass permissions param as "nil or email" in "[FBSessio openActiveSessionWithReadPermissions..." method. Here my code it was works great.
#define IOS_NEWER_OR_EQUAL_TO_6 ( [ [ [ UIDevice currentDevice ] systemVersion ] floatValue ] >= 6.0 )
-(void)showFBLogin
{
[FBSession.activeSession closeAndClearTokenInformation];
NSArray *permissions = [NSArray arrayWithObjects:#"email, publish_actions, publish_stream", nil];
#ifdef IOS_NEWER_OR_EQUAL_TO_6
permissions = nil; or NSArray *permissions = [NSArray arrayWithObjects:#"email",nil];
#endif
NSLog(#"\npermissions = %#", permissions);
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
NSLog(#"\nfb sdk error = %#", error);
switch (state) {
case FBSessionStateOpen:
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection, NSDictionary<FBGraphUser> *user, NSError *error) {
if (!error) {
//success
}
}];
break;
case FBSessionStateClosed:
//need to handle
break;
case FBSessionStateClosedLoginFailed:
//need to handle
break;
default:
break;
}
}];
}
I have the same problem on 3.1.3 FB SDK with iOS7.1. And I find a solution here. Hope it help!!
I have tried all answers here.
#loganathan nil permissions, #ill_always_be_a_warriors fbResync.
All of those don't work for me.
But I found it will works well when I launch the same code in iPhone 7.1 simulator
(without SSO"Single Sign On")
The same code works well on old version iOS FB SDK(not sure which version, but not 3.13)
(but no SSO will show when try to login)
So, I try to re-write a sample problem. I found several different here.
1. https://developers.facebook.com/docs/ios/getting-started Add new FacebookDisplayName
2. I modify my BundleID for iTune connect but I am not update it back to Faceboook App Dev
After modify those setting, it works on my iOS app with SSO feature.
Hope it help!!
Did you Try the RenewSystemCredential Methods? Take a look at this post:
Facebook iOS SDK extendAccessToken not Working - fbDidExtendToken not being called
I got the same error. But i used #ill_always_be_a_warriors method: -(void)fbResync but not work for me.
I finally found it's my permissions issue, i removed offline_access permission, it works, hope it helps some one.

How to restrict facebook default page to be displayed while login using facebook sdk

While using auto-login from native facebook, if I get logged out from native app then session won't work and facebook default login page get displayed. How could I detect that after which delegate or function of FBSession class is called after which the facebook default login page get displayed and restrict it to get displayed?
This is what I am doing to do a auto login
CacheToken = [[FBTokenCache alloc]init];
NSArray *permissions = [[NSArray alloc]initWithObjects:#"email,user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins", nil];
self.fbsession = [[FBSession alloc] initWithAppID:#"484473011575776"
permissions:permissions
urlSchemeSuffix:nil
tokenCacheStrategy:CacheToken];
(fbsession is the object of Facebook SDK class FBSession)
[FBSession setActiveSession:self.fbsession];
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
You can user facebook old sdk. In facebook.m just allow your app to open within app i.e trySafari = FALSE; and tryFBApp = FALSE;
I am using this.
Hope this will also help you.

Facebook Login ask to install (iPhone)

I need help in the facebook login from Facebook-SDK-3.1 for iOS 6.I have used all the code of the Facebook sdksample code sessionLoginSample,I have used the WebView opening code in this and whenever i login from the new id ...it takes me to the below image link to install in my project .dont know what exactly it is...and if i do so and after that logout from the code ..and when I again press button to login , it automatically log-in without asking for the id and pssword``login page. and again again it automatically logs-in , even after logout./.can anyone help me why after being logout it ask stores the previous access token and password.
and code is
- (IBAction)buttonClickHandler:(id)sender {
AppDelegate* appDelegate = [[UIApplication sharedApplication]delegate];
if (appDelegate.session.isOpen) {
[appDelegate.session closeAndClearTokenInformation];
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
appDelegate.session = [[FBSession alloc] initWithPermissions:[NSArray arrayWithObjects:#"email", nil]];
}
[appDelegate.session openWithBehavior:FBSessionLoginBehaviorForcingWebView
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
FBSession.activeSession = session;
[self updateView];
NSLog(#" state=%d",state);
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error) {
userInfo = #"";
userInfo = user.username;
NSLog(#"string %#", userInfo);
[self checkfacebook];
}];
}]; }
}
FB grants access to your app once the user logs in . If the user wants to modify the privileges he can do it by loggin into fb and changing permissions. You might want to look into oAuth for further details.
As u login through new emailid it has to install your app for them...so,its asking for different login..but again u login with the same it will not ask...the answer for ur 2nd question is....is u doing something to the server side...bcoz there might be a provision on the server which remember user for few hour or few days...so,check with server side..if not working with server...reply me back i will try to answer further...

Fetch cached access token through FBSession using Facebook SDK

Is there a way to fetch cached access token through FBSession using Facebook SDK if the user is logged in native Facebook.
I am trying to implement autologin through Facebook in an app i.e.when a user is logged in native Facebook then the app should not ask for the login and user should get automatically logged in.
I have used FBSession and FBTokenCacheStrategy and the user is getting logged in automatically but I am not able to fetch the access token which I need to call some API. The following code I am using to get this done :
CacheToken = [[FBTokenCache alloc]init];
NSArray *permissions = [[NSArray alloc]initWithObjects:#"email,user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins", nil];
self.fbsession = [[FBSession alloc] initWithAppID:#"484473011575776"
permissions:permissions
urlSchemeSuffix:nil
tokenCacheStrategy:CacheToken];
(fbsession is the object of Facebook SDK class FBSession)
[FBSession setActiveSession:self.fbsession];
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
Thanks in advance.
To get the access token you should use this:
[FBSession activeSession] accessToken]
However, it seems like you want to check whether there is already a (cached) access token. To do this you can do this:
// See if we have a valid token for the current state.
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
NSLog(#"The value access token is: %#", [[FBSession activeSession] accessToken]);
} else {
// No, display the login page.
}
Make sure also to do this in your app delegate or the access token will be nil:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// We need to properly handle activation of the application with regards to Facebook Login
// (e.g., returning from iOS 6.0 Login Dialog or from fast app switching).
[FBSession.activeSession handleDidBecomeActive];
}
Hope this helps
Try following code..
if (FBSession.activeSession.isOpen)
{
NSString *token = [[[FBSession activeSession] accessTokenData] accessToken];
}
hope this will work out for you..

How to login just in time to facebook in iOS app

Have reviewed the facbook pages on how to integrate facebook with iOS, but what i had been looking for is a bit different.
I would like to prompt for Facbook login only when a user decides to share stuff, the flow explained in FB docs walk thru how to login (handle asyc response from FB login) and show publish button, but what we need is to show "Post to FB" button, when the user clicks, i would like the user to login and then go to the preview of what is going to be posted and then post to FB.
I am using FB SDK and iOS 5, the difficulty is how to wire FB login flow directly to Post flow.
Thanks
Elango
Below is some code that I wrote that does this. If the user has not signed in to Facebook from the device settings, it is a better user experience to just call openActiveSessionWithPublishPermissions:, which does both the read and publish permissions in one step. Otherwise, you just do the two permissions serially. As soon as the read permission succeeds, you do the publish permission.
I tested this code on an iOS6 and iOS5 device, using Facebook SDK 3.2.1
- (BOOL)hasFacebookInDeviceSettings
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *accountTypeFB = [accountStore accountTypeWithAccountTypeIdentifier:#"com.apple.facebook"];
BOOL hasFacebookBuiltinAccount = (accountTypeFB != nil);
return hasFacebookBuiltinAccount;
}
- (BOOL)hasLoggedInToFacebookInDeviceSettings
{
if (![self hasFacebookInDeviceSettings]) {
return NO;
}
BOOL result = [SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook];
return result;
}
- (void)openFacebookSessionWithAllowLoginUI:(BOOL)allowLoginUI
{
if (![self hasLoggedInToFacebookInDeviceSettings]) {
// Simpler if we don't have the built in account
[FBSession openActiveSessionWithPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self facebookSessionStateChanged:session
state:state
error:error];
}];
}
else if (!FBSession.activeSession.isOpen) {
__block BOOL recursion = NO;
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
if (recursion) {
return;
}
recursion = YES;
if (error || !FBSession.activeSession.isOpen) {
[self facebookSessionStateChanged:session
state:state
error:error];
}
else {
assert(FBSession.activeSession.isOpen);
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound) {
[FBSession.activeSession requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session,
NSError *error) {
[self facebookSessionStateChanged:session
state:FBSession.activeSession.state
error:error];
}];
}
}
}];
}
}
hasFacebookInDeviceSettings tells you if this device even supports Facebook from the settings (i.e. this is iOS6+).
hasLoggedInToFacebookInDeviceSettings tells you if the user has signed into to Facebook from the iOS6 Facebook device settings.
You'll need to create your own facebookSessionStateChanged: and other code, as described in the login tutorial