Facebook login failing on iOS 6 - objective-c

When I try to login using Facebook iOS SDK I get the error The operation couldn't be completed (com.facebook.sdk error 2).
The state of the session is: FBSessionStateClosedLoginFailed.
THis is my code now:
-(void) callFBService{
NSArray *permissions = [[NSArray alloc] initWithObjects:#"email, publish_stream, user_likes, friends_likes", nil];
[FBSession openActiveSessionWithReadPermissions:permissions allowLoginUI:YES
completionHandler:^(FBSession *fbsession,
FBSessionState status,
NSError *error) {
if(error)
{
NSLog(#"Session error");
[self fbResync];
[NSThread sleepForTimeInterval:0.5]; //half a second
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *fbsession, FBSessionState status, NSError *error) {
[self sessionStateChanged:fbsession state:status error:error];
}];
}
else
[self sessionStateChanged:fbsession state:status error:error];
}];
}
I have tried everything in the following posts:
The operation couldn’t be completed. (com.facebook.sdk error 2.) ios6
Facebook Registration : The operation couldn't be completed (com.facebook.sdk error 2)
Facebook SDK 3.1 iOS: Handle login if user remove app from Facebook Settings
Any ideas??? Please!

You're passing publish_stream in with read permissions, but publish_stream is a write permission. It's also deprecated (use publish_actions instead). Try removing that permission. You'll need to ask for that permission separately, after you get your user logged in with read permissions. See the SDK docs: https://developers.facebook.com/docs/technical-guides/iossdk/login/#read
In addition, a few things to check: Make sure your app on Facebook.com is configured correctly, including the bundle ID. Make sure the user you're attempting to log in has rights to the app (if the app is in sandbox mode, make sure the user is added as a tester and has approved this).

Related

openActiveSessionWithPublishPermissions show login form twice

I'm trying to implement post wall using objective-c but when i do request new permission to 'publish_actions' with action session, the FB SDK login form is show again.
I'm looking for this tutorial: https://developers.facebook.com/docs/ios/publish-to-feed-ios-sdk/
In my application flow is basically this:
void (^completionHandler)(FBSession*, NSError*) = ^(FBSession*session, NSError*error){
if (session.isOpen && !error)
{
[FBWebDialogs presentFeedDialogModallyWithSession:session
parameters:params
handler:handler];
}
};
// abrie o dialog
BOOL isFBIntegration = [SLComposeViewController isAvailableForServiceType:SLServiceTypeFacebook];
if ([FBSession.activeSession.permissions indexOfObject:#"publish_actions"] == NSNotFound)
{
if(isFBIntegration)
{
[[FBSession activeSession] requestNewPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:completionHandler];
}
else
{
[FBSession openActiveSessionWithPublishPermissions:#[#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceEveryone
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
completionHandler(session, error);
}];
}
}
else
{
completionHandler(FBSession.activeSession, nil);
}
The user is already logged in because I do ask him to log when it enters the application:
HOME
[FBSession openActiveSessionWithReadPermissions:#[#"basic_info, user_friends, friends_interests"]
allowLoginUI:YES
completionHandler:nil];
When Facebook is native integration, all right, but when no, openActiveSessionWithPublishPermissions show login form again.
thank you.
Facebook iOS SDK 3.1 has now disabled openActiveSessionWithPublishPermissions. You will need to first establish a read only session, then additionally request write permissions. You can read more details about the upgrade process at iOS SDK Upgrade Guide.

Facebook: login and permission screen does not close when I return to my app

I am integrating facebook login in my application.
When I request the user for permissions the default UI get presented to him in order to accept the permissions, and then when he clicks on "okay" it will return from the ui to my app in order to continue.
However the default Permission UI remains open in the browser (if I quit the application and open the browser I still see the permission UI that was presented to him earlier.
Is there a way I can close the page in the browser after the user gives permission?
Hope I was clear
This is the code I am using:
This method will show the user the facebook login page in order to get his permission
-(BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_location",
#"user_birthday",
nil];
return [FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self HandleLogin];
}];
}
Then if login and permission successful
- (void)HandleLogin {
if (FBSession.activeSession.isOpen) {
[FBRequestConnection
startForMeWithCompletionHandler:^(FBRequestConnection *connection,
id<FBGraphUser> user,
NSError *error) {
//DO SOMETHING WITH THE USER INFO
}];
}
}
The code to process the return from the Facebook app
- (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];
}
Facebook SDK is pretty problematic, I'd say. Personally, I had displeasure to integrate FB picture sharing into several projects (while their developers released several new SDKs). I don't know, why browser redirection becomes popular, honestly, I don't like it. Generally, I don't think that it is possible to somehow clear this unwanted content from your browser without opening new url from application since it is not a solution. What I'd suggest is to force FB SDK to use WebView. In last version I used, this is set when you create new session with custom behavior. Code should be like this or pretty similar:
[[FBSession activeSession] openWithBehavior:FBSessionLoginBehaviorForcingWebView
completionHandler:^(FBSession *session, FBSessionState status, NSError *error)handler]

Handle invalid accessToken with FBSession openActiveSessionWithReadPermissions in Facebook iOS 3.1.1 SDK

Before anything, I have read both this and this questions to solve the problem below and before asking.
My problem is that when the accessToken gets expired (either because the expiration date passes, or manually by deleting the app from my Facebook's App Center) the following code:
if ([[FBSession activeSession] isOpen]) {
//do something
}
else {
[FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if(FB_ISSESSIONOPENWITHSTATE(status)) {
//do something
}
}
}];
}
gets in the else block with FBSession.activeSession open but when the 'do something' is executed the accessToken is invalid so the request gets Error: HTTP status code: 400.
When I try to do the whole procedure twice immediately the FBSession asks for permission (either UIAlertView for iOS6 integrated facebook, Facebook App or Facebook website in Safari) and the rest runs smoothly.
My concern is why I have to do everything twice to work well and why Facebook SDK cannot detect in the first time that the activeSession and accessToken are invalid.
Thank you all in advance!
The questions you linked are relevant, especially Facebook SDK 3.1 - Error validating access token which explains the problem where the Facebook account on the device is out of sync with the server (I.e., if you deleted the app from App Center). As mentioned there, in 3.1.1 the SDK will call to renew the device token only when it gets the invalid response from the server. This is a trade off in convenience for less round-trips to the server.
Assuming your code block is executed on applicationDidFinishLaunching or something similar, it will go to the else block because the app starts with a new session. When it calls openActiveSessionWithReadPermissions, the iOS 6 device thinks the token is valid and will let the state go to Open, so then your "do something" gets executed. Only then does the SDK get the invalid response from the server and invalidate the device token. As a result, the next time the procedure is called, it will prompt the user appropriately to authorize again.
This is intentional. For now, you can consider a automatic retry in your application if the error code describes an invalid token. For example, see the Scrumptious sample postOpenGraph retry code. In your case, it may look closer to something like (I used requestForMe as the "do something" for demonstration purposes):
else {
[FBSessionopenActiveSessionWithReadPermissions:nil allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if(FB_ISSESSIONOPENWITHSTATE(status)) {
//do something
[[FBRequest requestForMe] startWithCompletionHandler:^(FBRequestConnection *connection, id result, NSError *error) {
if (!error){
NSLog(#"success on first try");
} else if ([[error userInfo][FBErrorParsedJSONResponseKey][#"body"][#"error"][#"code"] compare:#190] == NSOrderedSame) {
//requestForMe failed due to error validating access token (code 190), so retry login
[FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:YES completionHandler:^(FBSession *session, FBSessionState status, NSError *error) {
if (!error){
//do something again, or consider recursive call with a max retry count.
NSLog(#"success on retry");
}
}];
}
}];
}
}];
}

Access Facebook Accounts on OS X Mountain Lion

As Mountain Lion now officialy has Facebook integrated I wanted to play a little bit with Accounts.framework and Social.framework of OS X.
I set up an App in the Facebook Developer App and used the following code to request access to the Facebook Accounts of the logged in user:
ACAccountStore *acStore = [[ACAccountStore alloc] init];
ACAccountType *accType = [acStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:FB_APP_ID, ACFacebookAppIdKey, #"read_stream, publish_stream", ACFacebookPermissionsKey, ACFacebookAudienceFriends, ACFacebookAudienceKey, nil];
[acStore requestAccessToAccountsWithType:accType options:options completion:^(BOOL granted, NSError *error) {
if (granted) {
NSLog(#"Accounts: %#", acStore.accounts);
NSLog(#"Access granted");
} else {
NSLog(#"Access denied");
}
}];
Now I always get the error Error Domain=XPCObjectsErrorDomain Code=2 "The operation couldn’t be completed. (XPCObjectsErrorDomain error 2.)"
When I launched the App from Xcode the first 2-3 times, OS X displayed the confirmation dialog "XYZ wants to access your Facebook Accounts", I clicked ok and I got an error saying something like "The Application is not yet installed". This error now "disappeared" and I'm getting the error noted above.
My question is: Do I have to configure something special in my Xcode Project (Info.plist) or in the Facebook Developer App to make it work with OS X? Or am I missing something in the code? Samples and Tutorials regarding this seem to be very rare :-/
I already watched the WWDC 2012 Video about the Twitter/Facebook Integration but it uses almost exactly the code I used.
Any help is appreciated :-)
Cheers,
Björn
Update
I solved the issue, I just did not read the docs carefully enough ;-) I have to pass the permissions as an NSArray and not as a string. I've modified the options dictionary to look like this:
NSDictionary *options = [NSDictionary dictionaryWithObjectsAndKeys:
FB_APP_ID, ACFacebookAppIdKey,
[NSArray arrayWithObjects:#"read_stream", #"publish_stream", #"email", #"user_likes", nil], ACFacebookPermissionsKey,
ACFacebookAudienceFriends, ACFacebookAudienceKey, nil];
Now OS X shows an alert that asks me if I want to allow the App to post to Facebook on my behalf, I click OK and a new error appears resulting in no access to the Facebook accounts:
Error Domain=com.apple.accounts Code=7 "The Facebook server could not fulfill this access request: The app must ask for a basic read permission at install time."
I already modified the permissions to be just email or just user_likes but it all resulted in the same error. If I only request access to read_stream the access gets granted but results in the OAuth error 190 with the message Error validating access token: User XXXXXX has not authorized application XXXXXX.
Update 2:
I now solved all my problems, see my answer below.
Alright, I finally solved it :-)
When you first request access to a users Facebook accounts, you may only request permissions from the user listed under "User and Friend permissions" in Facebook's Permission Reference.
Once the user granted access and with that also installed the application on Facebook, you may request any additional permissions required by your App. It's important that you may not ask for read and write permissions at the same time, one after the other! So requesting the permission read_stream and publish_stream in the same request will not work.
This is the basically the code I used:
self.store = [[ACAccountStore alloc] init];
ACAccountType *accType = [self.store accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSMutableDictionary *options = [NSMutableDictionary dictionaryWithObjectsAndKeys:
FB_APP_ID, ACFacebookAppIdKey,
[NSArray arrayWithObjects:#"email", #"user_about_me", #"user_likes", nil], ACFacebookPermissionsKey, ACFacebookAudienceFriends, ACFacebookAudienceKey, nil];
[self.store requestAccessToAccountsWithType:accType options:options completion:^(BOOL granted, NSError *error) {
if (granted && error == nil) {
self.accounts = self.store.accounts;
[options setObject:[NSArray arrayWithObjects:#"read_stream, read_mailbox, read_requests", nil] forKey:ACFacebookPermissionsKey];
[self.store requestAccessToAccountsWithType:accType options:options completion:^(BOOL granted, NSError *error) {
if (granted && error == nil) {
completionHandler(granted, error);
} else {
NSLog(#"Access denied 2");
NSLog(#"%#", [error description]);
}
}];
} else {
NSLog(#"Error: %#", [error description]);
NSLog(#"Access denied");
}
}];
Hope this will help somebody :-)
I would like to add that there is an additional caveat in the Facebook docs:
// if a user has *never* logged into your app, you MUST include one of
// "email", "user_location", or "user_birthday". Other read
// permissions can also be included here.
Failure to do this leads to the same error.

How do I cancel a previous Facebook reauthorize call?

A quick question about the Facebook SDK for iOS. I'm trying to implement the functionality for a user to grant my app access to extended permissions.
While the code works fine when the user accepts the extended permission request (from the Facebook iOS app the user gets redirected to), I'm having trouble detecting when the user has returned to the app while having neither accepted the permissions, or clicking cancel then returning to the app.
If I click 'Cancel' and multitask back into the app, there is nothing logged and nothing shown on-screen. When I try to re-authorize again, the Facebook SDK throws an exception:
FBSession: It is not valid to reauthorize while a previous reauthorize call has not yet completed.
While I can catch the exception, it still doesn't help as I can't figure out how to stop the previous call in order to allow the user to try to re-authorize again.
Here's the code I'm using at the moment:
#try {
[[FBSession activeSession] reauthorizeWithPermissions:[self requiredPermissions]
behavior:FBSessionLoginBehaviorWithFallbackToWebView
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
[self fetchUserPermissionsWithCompletionHandler:^(BOOL extendedGranted) {
if (extendedGranted) {
[self setCanPostToActivityStream:YES];
}
}];
}
else {
NSLog(#"%#", [error localizedDescription]);
}
}];
}
#catch (NSException *exception) {
NSLog(#"%#", exception);
}
Now, the issue is not with the code above - the code works fine. The issue I'm having, again, is cancelling the previous re-authorize call when the user doesn't return to the app successfully after allowing permissions. The Facebook SDK as it is doesn't seem to alert the app of this situation in any way.
From your App's delegate, when - (void)applicationDidBecomeActive:(UIApplication*)application is invoked, you need to make a call to the active session's handleDidBecomeActive method. Once you do that, the completion handler associated with your reauthorizeWithPublishPermissions call will be invoked, and will provide the appropriate error.
- (void)applicationDidBecomeActive:(UIApplication*)application
{
[[FBSession activeSession] handleDidBecomeActive];
}
What you should see coming back from the SDK is an error from the reauthorize completion handler.
{
"com.facebook.sdk:ErrorLoginFailedReason" = "com.facebook.sdk:ErrorReauthorizeFailedReasonUserCancelled";
}
I tested something similar with the following setup: Xcode 4.5, iOS 5, Authorize against m.facebook.com. After an initial authorization I put code to hit reauthorize, then clicked Cancel and got this error.
[FBSession.activeSession
reauthorizeWithPublishPermissions:
[NSArray arrayWithObject:#"publish_actions"]
defaultAudience:FBSessionDefaultAudienceFriends
completionHandler:^(FBSession *session, NSError *error) {
if (!error) {
// Success case
} else {
// Check the error, info
// [[error userInfo] objectForKey:#"com.facebook.sdk:ErrorLoginFailedReason"]
}
}];
If you are not seeing this then it is a bug and you may want to file it with Facebook.