Facebook sharekit 2.0 troubles - iphone

- (void)authorize:(NSArray *)permissions {
self.permissions = permissions;
[self authorizeWithFBAppAuth:NO safariAuth:NO];
}
Ok, the above code is what I am trying to implement. But this code is giving me two errors. The first one is property permission not found in Facebook and second one is instance authorize authorizeWithFBAppAuth: not found.This is share kit 2.0 so maybe this will not work on it, but I need to stop the Facebook app popping up. P.S. I am a Sharekit noob.
- (void)authorize:(NSArray *)permissions {
// if we already have a session, git rid of it
[self.session close];
self.session = nil;
[self.tokenCaching clearToken];
self.session = [[[FBSession alloc] initWithAppID:_appId
permissions:permissions
urlSchemeSuffix:_urlSchemeSuffix
tokenCacheStrategy:self.tokenCaching]
autorelease];
[self.session openWithCompletionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
switch (status) {
case FBSessionStateOpen:
// call the legacy session delegate
[self fbDialogLogin:session.accessToken expirationDate:session.expirationDate];
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]);
// call the legacy session delegate
[self fbDialogNotLogin:userDidCancel];
}
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
}
}];
}
This code above is the original that came with share kit 2.0, if there is a way to stop Facebook app popping up in the above code please let me know.

Use like below:
- (void)authorize:(NSArray *)permissions
{
self.permissions = permissions;
[self authorizeWithFBAppAuth:NO safariAuth:YES];
}
And then check.

Related

Facebook iOS SDK Login Fails On First Attempt but Successful on Second

Ok, so this has been a tough one for me to debug because I do not experience this problem that many users of my app appear to be experiencing. If you would like to try it yourself, you may download the app on iTunes by searching for "syncquik".
PROBLEM: When users attempt to login to my app via the Facebook login button, the first attempt to open an active FB session often fails. At first, I thought this was because they had to turn on the app's Facebook privacy settings in the iPhone's general settings. However, because so many are having the same issue, I am beginning to wonder if it's because of an error in my code (see below)? I followed the demo example and Facebook instructions, but perhaps I missed something? Thanks in advance for any help you can offer!
CODE:
(In ViewController holding FB button):
- (IBAction)fbSignIn:(id)sender
{
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
[appDelegate openSession];
}
(In AppDelegate.m):
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
NSLog(#"FB Session State Changed");
switch (state) {
case FBSessionStateOpen: {
NSLog(#"FBSessionStateOpen");
if (fbButtonPushed && FBSession.activeSession.isOpen) {
[self sendUserFbInfo];
fbButtonPushed = NO;
}
}
break;
case FBSessionStateClosed:
NSLog(#"FBSessionStateClosed");
break;
case FBSessionStateClosedLoginFailed:
NSLog(#"FBSessionStateClosedLoginFailed");
[FBSession.activeSession closeAndClearTokenInformation];
[self showLoginView];
break;
default:
break;
}
if (error) {
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:#"Please Try Again" message:#"If second attempt is unsuccessful, then set SyncQuik to ON in Settings > Facebook." delegate:self cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alertView show];
[[NSNotificationCenter defaultCenter] postNotificationName:#"com.syncquik.connectionrequest.complete" object:nil];
}
}
- (void)openSession
{
NSLog(#"Opening a User's FB Session");
fbButtonPushed = YES;
NSArray *permissons = [[NSArray alloc] initWithObjects:#"email", nil];
[FBSession openActiveSessionWithReadPermissions:permissons
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
- (void)showLoginView
{
NSLog(#"Show Login View");
//Anything else need to be placed here?
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
[FBSession.activeSession handleDidBecomeActive];
if (fbButtonPushed && FBSession.activeSession.isOpen) {
[self sendUserFbInfo];
fbButtonPushed = NO;
}
}
if (self.session.state != FBSessionStateCreated) {
// Create a new, logged out session.
[self openSession];
}
else{
[FBSession setActiveSession:self.session];
[self sessionStateChanged:session state:state error:error];
}
try this code in openActiveSessionWithReadPermissions block

FBWebDialog rotation issue in iPad

When I use following code to open FBWebDialog, Once FBWebDialog is open click in username textfield and keyboard is displayed now if you rotate iPad device, FBWebDialog is not auto-rotating to landscape orientation.
[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
}
}];
Following are steps to reproduce this issue :
Open FBWebialog which opens inside iPad app
Click in username textfield and keyboard is displayed
Now if you rotate iPad device, FBWebDialog is not auto-rotating to landscape orientation.
Please help me to solve this issue....
Its bug from facebook side, here is the my query posted to the facbook support team. Even not getting any kind of response from Facebook,its ridicules...
https://developers.facebook.com/bugs/355080977928726?browse=external_tasks_search_results_52820409e9c884976463112

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.

Close Facebook session in Facebook-Ios-Sdk

How do I close aCtive Session Of the Facebook-iOS-Sdk each time when i start my app either after killing app it gives me the previous login session details. When I click on the facebook Button .I have used everything [appDelegate.session closeAndClearTokenInformation];
[FBSession.activeSession close]; [FBSession.activeSession closeAndClearTokenInformation] ..but active session still not been close..how do i close the Previous session data on clicking.
I use the below code to clear but whenever I click on the facebook button to start new session..it gives me back the previous credentials.
- (IBAction)buttonClickHandler:(id)sender {
appDelegate = [[UIApplication sharedApplication]delegate];
// this button's job is to flip-flop the session from open to closed
if (appDelegate.session.isOpen) {
[appDelegate.session closeAndClearTokenInformation];
[FBSession.activeSession close];
[FBSession.activeSession closeAndClearTokenInformation];
FBSession.activeSession=nil;
} else {
if (appDelegate.session.state != FBSessionStateCreated) {
// Create a new, logged out session.
appDelegate.session = [[FBSession alloc] init];
}
// if the session isn't open, let's open it now and present the login UX to the user
[FBSession.activeSession closeAndClearTokenInformation];
FBSession.activeSession=nil;
[FBSession.activeSession openWithBehavior:FBSessionLoginBehaviorForcingWebView
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
// and here we make sure to update our UX according to the new session state
NSLog(#" state=%d",state);
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error) {
userInfo = #"";
// Example: typed access (name)
// - no special permissions required
userInfo = user.username;
NSLog(#"string %#", userInfo);
[self checkfacebook];
}];
}]; }
}
and in ViewDidLoad
- (void)viewDidLoad
{
[super viewDidLoad];
AppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
if (!appDelegate.session.isOpen) {
// create a fresh session object
appDelegate.session = [[FBSession alloc] init];
if (appDelegate.session.state == FBSessionStateCreatedTokenLoaded) {
// even though we had a cached token, we need to login to make the session usable
[FBSession.activeSession close];
FBSession.activeSession=nil;
}
}
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
NSArray* facebookCookies = [cookies cookiesForURL:[NSURL URLWithString:#"http://login.facebook.com"]];
for (NSHTTPCookie* cookie in facebookCookies) {
[cookies deleteCookie:cookie];
}
}
hi Christien may be bellow two link its help's you please refur this two link of developers.facebook
http://developers.facebook.com/docs/reference/ios/3.0/class/FBSession/
http://developers.facebook.com/docs/reference/ios/3.0/class/FBSession/#close
[FBSession.activeSession closeAndClearTokenInformation];
[FBSession.activeSession close];
[FBSession setActiveSession:nil];
you can also check this two question related your issue :-
Facebook graph api log out not working
Facebook iOS SDK 3.1.1 "closeAndClearTokenInformation" method no working
hope its helps you
After calling
[FBSession.activeSession closeAndClearTokenInformation];
use following to clear cookies. It worked for me!
NSHTTPCookieStorage* cookies = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (NSHTTPCookie* cookie in
[[NSHTTPCookieStorage sharedHTTPCookieStorage] cookies]) {
[cookies deleteCookie:cookie];
}
Nitin's Gohel answer, Swift version:
FBSession.activeSession().closeAndClearTokenInformation()
FBSession.activeSession().close()
FBSession.setActiveSession(FBSession())
you can use
FBSession.setActiveSession(nil)
But the function ask for an unwrapped object, so "nil" seems not a good parameter to be pass

FBSession often fails to be at FBSessionStateCreatedTokenLoaded when returning to foreground

I am using Facebook iOS SDK3.0 (client is not ready to move to 3.1 yet), and have been having trouble to get FBSession to be at the FBSessionStateCreatedTokenLoaded when the app returns to the foreground after a longer period of time (close to a day); I don't have issue if I just send the app to background and come back to the foreground after a minute or two
my code is as follow, please let me know if I should provide further information; I have this issues across devices (4, 4S, 5) and iOS version (4.3, 5.0, 5.1, 6.0)
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
...
if (![self openSessionWithAllowLoginUI:NO]) {
// still allow loading the public feed even though user is not logged in (the view controller will have a login button overlay)
[[self pictureFeedVC] loadFeed];
}
...
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
DEBUGLog(#"didBecomeActive");
DEBUGLog(#"FBSession is Open? %#",FBSession.activeSession.isOpen ? #"YES" : #"NO");
if (FBSession.activeSession.state == FBSessionStateCreatedOpening) {
//Dismiss login view controller
if ([self.tabBarController modalViewController]) {
[self.tabBarController dismissModalViewControllerAnimated:NO];
}
[FBSession.activeSession close];
}
}
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
BOOL result = NO;
[FBSettings setLoggingBehavior:[NSSet setWithObjects:FBLoggingBehaviorSessionStateTransitions,nil]];
NSArray *permissions = [NSArray arrayWithObjects:#"publish_actions", #"email", nil];
FBSession *session = [[FBSession alloc] initWithAppID:nil permissions:permissions urlSchemeSuffix:FB_URL_SCHEME_SUFFIX tokenCacheStrategy:nil];
if (allowLoginUI || (session.state == FBSessionStateCreatedTokenLoaded)) {
[FBSession setActiveSession:session];
[session openWithCompletionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
result = session.isOpen;
}
return result;
}
- (void)sessionStateChanged:(FBSession *)session state:(FBSessionState)state error:(NSError *)error
{
DEBUGLog(#"changed FB state");
switch (state) {
case FBSessionStateOpen:
if (!error) {
DEBUGLog(#"FBSessionStateOpen");
[[self pictureFeedVC] loadFeed];
}
break;
case FBSessionStateClosed:
DEBUGLog(#"FBSessionStateClosed");
case FBSessionStateClosedLoginFailed:
DEBUGLog(#"FBSessionStateClosedLoginFailed");
[session closeAndClearTokenInformation];
[self.tabBarController showFBLoginView];
break;
default:
break;
}
}
I am having problem where after extended period in the background, the DEBUGLog(#"FBSession is Open? %#",FBSession.activeSession.isOpen ? #"YES" : #"NO"); in applicationDidBecomeActive: will print a NO
more info: this app relies on Facebook login entirely, it uses facebook user ID to identify users, therefore for lots of actions I need to pass the Facebook access token so that the server can get the facebook user ID even though a lot of times those actions does not require api calls to facebook (besides getting the user ID from the access token of course). My other question is whether I need to actively do something to refresh the token or do something keep the FBSession open (if so, how?), would that be the reason why the FBSession.activeSession might not be in an open state when I return to foreground?
Thanks much in advance!