FBSDKLoginManager logInWithPublishPermissions always returns isCancelled=YES - ios

I am having trouble figuring out how to log a user into my app. [FBSDKAccessToken currentAccessToken] is nil, so I am calling:
[[[FBSDKLoginManager alloc] init] logInWithPublishPermissions:#[#"publish_actions"] handler:…];
as per the included sample project. This switches to the Facebook app, but the message says "You have already authorized App Name.". I click OK and it goes back into the app, but grantedPermissions and declinedPermissions are both nil on the result, and isCancelled is YES. [FBSDKAccessToken currentAccessToken] is still nil.
I can't figure out how I'm supposed to get currentAccessToken to be filled in. It seems to me the call to logInWithPublishPermissions should do that, but it isn't.

You should try adding in your AppDelegate didFinishLaunchingWithOptions :
return [[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
This would get u [FBSDKAccessToken currentAccessToken] when user is logged in.
and
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
return [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
}
If this method is not present into AppDelegate then it results into cancelled state.
Refer to : https://developers.facebook.com/docs/ios/getting-started#startcoding

This can happen when your Facebook App doesn't have "publish_actions" permission, or you're not using a test user.
On Facebook, go to manage your app, then make sure that the Facebook user you're using is defined under "Roles" as an admin or tester.
If it's not a test user or admin - Facebook will require "publish_actions" permission to be reviewed and approved before allowing your app to use it, until then you'll receive a "isCancelled=YES" result.
After testing your app with this permission, it is possible to submit this permission for review, you'll need to upload a binary that demonstrates usage of this permission with exact details on how to use it. After it's approved, you'll be able to use it with non-test Facebook users.

Since FBSDKLoginKit 4.6.0, the logInWithReadPermissions and logInWithPublishPermissions methods of FBSDKLoginManager seems to have additional fromViewController argument and use that to present modals.
I was calling logInWithPublishPermissions inside the callback of logInWithReadPermissions, which at that point the modal is not fully dismissed yet. (I know it's a bad practice to ask permission when it's not needed, but in my case this seems to be the right place to do.) This cause it to fail with isCancelled equals to YES. I added some delay and wait for the modal to be fully dismissed fixed the problem.

I had the same problem when I landed here, turns out I was only using the deprecated application openURL method because i was using google sign in too. To support iOS 8 and before you have to implement both the current and the deprecated method:
func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
return GIDSignIn.sharedInstance().handle(url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!, annotation: options[UIApplicationOpenURLOptionsKey.annotation]) || FBSDKApplicationDelegate.sharedInstance().application(app, open: url, sourceApplication: options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String, annotation: options[UIApplicationOpenURLOptionsKey.annotation])
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return GIDSignIn.sharedInstance().handle(url, sourceApplication: sourceApplication, annotation: annotation) || FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
The deprecated is the second.
Note: The FBSDK method is added after the google one with an or "||" operator but the order doesn't matter and if you wanna only use facebook method just erase the method and the or operator.
Note 2: As swift 3 still stabilizing the method name can change I suggest you always use the auto complete from XCode when overriding and implementing a delegate's method.
Hope this Helps o/

FBSDKLoginManagerLoginResult.isCancelled is unexpectedly YES:
The SDK will report a cancellation if the user explicitly taps a cancel button in the login dialogs, or if they manually app switch back to your app (known as an implicit cancellation). You should make sure you are not initiating a login flow as part of your app delegate's lifecycle (such as starting a login inside application:openURL:sourceApplication:annotation:) as that will mimic an implicit cancellation. If you must, dispatch the login initiation later to the main queue so that the app delegate's lifecycle completes first.

This method works in iOS 9
// Facebook Login Completion delegate
- (void)loginButton:(FBSDKLoginButton *)loginButton didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result error:(NSError *)error
{
if (result){
NSLog(#"%#",result);
NSLog(#"%#",result.grantedPermissions);
[self getFacebookData:result];
}
}
- (void)getFacebookData:(FBSDKLoginManagerLoginResult *)result{
if (![result.grantedPermissions containsObject:#"email"])
{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
login.loginBehavior = FBSDKLoginBehaviorWeb;
[login logInWithReadPermissions:#[#"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
// Process error
}
else if (result.isCancelled)
{
// Handle cancellations
}
else
{
if ([result.grantedPermissions containsObject:#"email"])
{
NSLog(#"result is:%#",result);
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"first_name, last_name, email, id"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%#", result);
[self registerWithFacebook:result];
}else{
NSLog(#"%#",error);
}
}];
}
}
}
}];
}else{
if ([FBSDKAccessToken currentAccessToken]) {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"first_name, last_name, email, id"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
NSLog(#"fetched user:%#", result);
[self registerWithFacebook:result];
}else{
NSLog(#"%#",error);
}
}];
}
}
}
NOTE : Use FBSDKLoginBehaviorWeb instead of FBSDKLoginBehaviorBrowser. This will surely work

Also, make sure you are not calling for FBSDKAccessToken.currentAccessToken INSIDE your didFinishLaunchingWithOptions method. The setup in didFinishLaunchingWithOptions needs to complete so the token can initialize before you try to log in to Facebook.

I also faced the same issue and i spent almost 2 hours to resolve the issue. What i did is
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
**[login logOut];** // adding this single line fixed my issue
[login logInWithReadPermissions: #[#"public_profile"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
NSLog(#"Process error");
} else if (result.isCancelled) {
NSLog(#"Cancelled");
} else {
NSLog(#"Logged in");
[self GetData];
}
}] // I called this logout function
and the issue was fixed
i was using both google and Facebook login so i had to implement my openURL method like this, iOS 9+
- (BOOL)application:(UIApplication *)app openURL:(NSURL *)url options:(NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options {
if ([[url absoluteString] containsString:#"YOURFBID"]) {
return [[FBSDKApplicationDelegate sharedInstance] application:app openURL:url options:options];
} else {
return [[GIDSignIn sharedInstance] handleURL:url
sourceApplication:options[UIApplicationOpenURLOptionsSourceApplicationKey]
annotation:options[UIApplicationOpenURLOptionsAnnotationKey]];
}
return NO;
}
// you can perform further any operations using the access token
- (void)GetData {
if ([FBSDKAccessToken currentAccessToken]) {
NSDictionary *AccessToken = [FBSDKAccessToken currentAccessToken];
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"id, name, first_name, picture.type(large) ,last_name"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error) {
//NSLog(#"fetched user:%#", result);
//NSDictionary *Result = result;
NSDictionary *params = [NSMutableDictionary dictionaryWithObject:[AccessToken tokenString] forKey:#"access_token"];
} else {
[self showAlertController:#"Error" message:error.localizedDescription];
}
}];
} }

(BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
options:(nonnull NSDictionary<UIApplicationOpenURLOptionsKey,id> *)options
{
return [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
options:options];
}
// **Still need this for iOS8**
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(nullable NSString *)sourceApplication
annotation:(nonnull id)annotation
{
return [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
}

1.check already added
[[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
2.check already added
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(nullable NSString *)sourceApplication
annotation:(nonnull id)annotation
{
return [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
}
3.
write this statement [FBSDKProfile enableUpdatesOnAccessTokenChange:YES];
before
[[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
4.call logInWithReadPermissions method in dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{}

call this methord,
FBSDKLoginManager *loginManager = [[FBSDKLoginManager alloc] init];
[loginManager logInWithReadPermissions:#[#"user_friends"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
code
}];

Related

iOS : Login with Facebook and open Native Facebook app

I Want open facebook application at login time that already install in the device for login authentication, but always open in the Safari browser.
- facebook button click
-(void)loginButtonClicked
{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
// [login setLoginBehavior:FBSDKLoginBehaviorNative];
[login logInWithReadPermissions:#[#"email"] fromViewController:self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
NSLog(#"Login process error");
}
else if (result.isCancelled)
{
NSLog(#"User cancelled login");
}
else
{
NSLog(#"Login Success");
if ([result.grantedPermissions containsObject:#"email"])
{
NSLog(#"result is:%#",result);
[self fetchUserInfo];
}
else
{
// [SVProgressHUD showErrorWithStatus:#"Facebook email permission error"];
}
}
}];
}
}
-here to fetch user info
-(void)fetchUserInfo
{
if ([FBSDKAccessToken currentAccessToken])
{
NSLog(#"Token is available : %#",[[FBSDKAccessToken currentAccessToken]tokenString]);
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:#{#"fields": #"id, name, email"}]
startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id result, NSError *error) {
if (!error)
{
NSLog(#"results:%#",result);
NSString *email = [result objectForKey:#"email"];
NSString *userId = [result objectForKey:#"id"];
if (email.length >0 )
{
NSString *accessToken = [[FBSDKAccessToken currentAccessToken] tokenString];
[ref authWithOAuthProvider:#"facebook" token:accessToken
withCompletionBlock:^(NSError *error, FAuthData *authData)
{
if (error)
{
NSLog(#"Login failed. %#", error);
}
else
{
NSLog(#"Logged in! %#", authData);
//Start you app Todo
}
else
{
NSLog(#"Facebook email is not verified");
}
}
else
{
NSLog(#"Error %#",error);
}
}];
}
I Want to open facebook application for login with facebook.
From V4.6.0 it won't redirect to fb app. See below
(v4.6.0 - September 10, 2015) In addition, the SDK dialogs such as
Login, Like, Share Dialogs automatically determine the best UI based
on the device, including SFSafariViewController instead of Safari.
Follow the our Preparing for iOS 9 guide.
Please Use FBLoginView as Facebook SignIn button It automatically detects Facebook app & u can able to login with facebook.
FBLoginView class available in Facebook SDK.
Please set info.plist parameters properly, you may have not provided the URLs like this
<array>
<dict>
<key>CFBundleURLSchemes</key>
<array>
<string>fb776035152513539</string>
</array>
</dict>
</array>
and
<key>FacebookAppID</key>
<string>776035152513539</string>
If you are not able to achieve what you want,then you can use these classes.
Header File -
//
// LxFaceBookHandler.h
// KickOffSlotMachine
//
// Created by Prakhar Goyal on 06/08/15.
// Copyright (c) 2015 LOGICNEXT. All rights reserved.
//
#import <Foundation/Foundation.h>
#import <FBSDKCoreKit/FBSDKCoreKit.h>
#import <FBSDKLoginKit/FBSDKLoginKit.h>
typedef NS_ENUM(NSInteger,LOGINRESPONSE)
{
LOGINRESPONSE_ERROR,
LOGINRESPONSE_CANCEL,
LOGINRESPONSE_SUCCESS
};
#protocol LxFaceBookHandlerDelegate <NSObject>
-(void)DidLogInWithResponse:(LOGINRESPONSE)type;
#end
#interface LxFaceBookHandler : NSObject
#property(weak,nonatomic)id<LxFaceBookHandlerDelegate>delegate;
-(void)InitFaceBookLogin;
//Called from app Delegate
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation;
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions;
#end
and Implementation file is -
//
// LxFaceBookHandler.m
// KickOffSlotMachine
//
// Created by Prakhar Goyal on 06/08/15.
// Copyright (c) 2015 LOGICNEXT. All rights reserved.
//
#import "LxFaceBookHandler.h"
#implementation LxFaceBookHandler
#synthesize delegate = __delegate;
- (instancetype)init
{
self = [super init];
if (self)
{
__delegate = nil;
}
return self;
}
-(void)InitFaceBookLogin;
{
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error)
{
if (error)
{
if (__delegate!=nil)
{
if ( [__delegate respondsToSelector:#selector(DidLogInWithResponse:)])
{
[__delegate DidLogInWithResponse:LOGINRESPONSE_ERROR];
}
}
}
else if (result.isCancelled)
{
if (__delegate!=nil)
{
if ( [__delegate respondsToSelector:#selector(DidLogInWithResponse:)])
{
[__delegate DidLogInWithResponse:LOGINRESPONSE_CANCEL];
}
}
}
else
{
if (__delegate!=nil)
{
if ( [__delegate respondsToSelector:#selector(DidLogInWithResponse:)])
{
[__delegate DidLogInWithResponse:LOGINRESPONSE_SUCCESS];
}
}
// if ([result.grantedPermissions containsObject:#"email"]) {
// // Do work
// }
}
}];
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
}
-(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
return [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
}
#end
Add FBSDKCoreKit.Framework and FBSDKLoginKit.Framework in your project and set your app Delefate like this -
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
self.window.backgroundColor=[UIColor blackColor];
SplashViewController *rVC = [[SplashViewController alloc] initWithNibName:#"SplashViewController" bundle:nil];
self.mNavController=[[UINavigationController alloc]initWithRootViewController:rVC];
[self.mNavController setNavigationBarHidden:YES];
self.window.rootViewController=self.mNavController;
[self.window makeKeyAndVisible];
self.handler = [[LxFaceBookHandler alloc]init];
[self.handler application:application didFinishLaunchingWithOptions:launchOptions];
return YES;
}
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [self.handler application:application openURL:url sourceApplication:sourceApplication annotation:annotation];
}
now you can use these classes as on any event suppose on button click-
- (IBAction)FacebookLoginPressed:(UIButton *)sender
{
App.handler.delegate = self;
[App.handler InitFaceBookLogin];
}

Facebook login: persisting across app launches

I'm logging in users with the following method, which works fine. However, each time the app relaunches, I need to run this method again to regain access.
The Facebook documentation seems to be very limited, and all the advice I can find (including on Stack Overflow) is related to the old Facebook SDK.
From what I can understand, a FBSDKAccessToken should be being cached when the user is first logged in. However, when I check [FBSDKAccessToken currentAccessToken] on subsequent launches, nothing is returned.
Any advice very welcome.
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithPublishPermissions:#[#"publish_actions"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
// Process error
} else if (result.isCancelled) {
// Handle cancellations
} else {
if ([result.grantedPermissions containsObject:#"publish_actions"]) {
// success
}
}
}];
Lol, searched for hours then came here 5 minutes too soon. The problem was that I needed to add the following in AppDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
return [[FBSDKApplicationDelegate sharedInstance] application:application
didFinishLaunchingWithOptions:launchOptions];
}
You ALSO want to add this in the following method:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation {
BOOL facebookCheck = [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
if (!facebookCheck){
...
}
return true;
}
You probably wont need it now, but it doesn't hurt. :)

Facebook and twitter login with Parse iOS only works once

I'm using the twitter and Facebook login in the Parse SDK. For every app launch I can log into each service once, but when I logout using [PFUser logOut] I am unable to log in again. The [PFFacebookUtils logInWithPermissions] block never gets called either with a user or an error.
My (Facebook) Login Code is:
- (IBAction)facebookLogin:(id)sender {
NSArray *permissionsArray = #[ #"user_about_me" ];
// Login PFUser using Facebook
[PFFacebookUtils logInWithPermissions:permissionsArray block:^(PFUser *user, NSError *error) {
if (!user) {
NSString *errorMessage = nil;
if (!error) {
NSLog(#"Uh oh. The user cancelled the Facebook login.");
errorMessage = #"Uh oh. The user cancelled the Facebook login.";
} else {
NSLog(#"Uh oh. An error occurred: %#", error);
errorMessage = [error localizedDescription];
}
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Log In Error"
message:errorMessage
delegate:nil
cancelButtonTitle:nil
otherButtonTitles:#"Dismiss", nil];
[alert show];
} else {
if (user.isNew) {
NSLog(#"User with facebook signed up and logged in!");
} else {
NSLog(#"User with facebook logged in!");
}
}
}];
}
My logout code is:
- (IBAction)loginButton:(id)sender {
if([PFUser currentUser]) {
[PFUser logOut];
NSLog(#"User is %#", [PFUser currentUser]);
NSLog(#"Facebook session is %#", [PFFacebookUtils session]);
NSLog(#"Facebook session is %#", FBSession.activeSession.observationInfo);
} else {
[self performSegueWithIdentifier:#"loginScreenSegue" sender:self];
}
}
Everything logs (null).
I assumed that as the behaviour was the same with Twitter, that it might be related to the OAuth related methods in my AppDelegate:
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [FBAppCall handleOpenURL:url
sourceApplication:sourceApplication
withSession:[PFFacebookUtils session]];
}
- (BOOL) application:(UIApplication *)application
handleOpenURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [FBAppCall handleOpenURL:url
sourceApplication:sourceApplication
withSession:[PFFacebookUtils session]];
}
But have done a lot of research and don't seem to be missing anything...
I also have these in the AppDelegate:
- (void)applicationWillResignActive:(UIApplication *)application {
[[PFFacebookUtils session] close];
}
- (void)applicationWillTerminate:(UIApplication *)application {
[[PFFacebookUtils session] close];
}
- (void)applicationDidBecomeActive:(UIApplication *)application {
[FBAppCall handleDidBecomeActiveWithSession:[PFFacebookUtils session]];
}
Any help would be very gratefully received!
In you logout method, you should clear the Facebook session token as well like below:
[[FBSession activeSession]closeAndClearTokenInformation];
This will clear the active Facebook session's token.
OK, I finally solved this. The problem was that in my app setup on twitter, the permissions were set to 'Read only', not 'Read and Write'.
Changing this setting solved the problem with both facebook and twitter.

How to Get URL when application launch via facebook?

I am sharing a facebook link using this method presentShareDialogWithLink in my application. When user tap on the post in facebook application then this opens my application automatically, at that time i want to get the url on what user tap in facebook application. How do i get that url and where i'll get that url?
You can get the URL by method handleOpenURL in AppDelegate
-(BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url {
/* Do something with the url */
}
If you've set up a handler during the present* call, something like:
[FBDialogs presentShareDialogWithLink:url
handler:^(FBAppCall *call, NSDictionary *results, NSError *error) {
if(error) {
NSLog(#"Error: %#", error.description);
} else {
NSLog(#"Success!");
}
}];
Then in your AppDelegate, override the application:openURL:sourceApplication:annotation: method:
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
BOOL urlWasHandled = [FBAppCall handleOpenURL:url
sourceApplication:sourceApplication
fallbackHandler:^(FBAppCall *call) {
NSLog(#"Unhandled deep link: %#", url);
}];
return urlWasHandled;
}
Then your handler should get a callback.
For more info, see https://developers.facebook.com/docs/ios/share-dialog/, in particular, https://developers.facebook.com/docs/ios/share-dialog/#handling-responses

iOS Facebook SDK delegate methods not called

I see this question asked in several other posts but nothing seems to work for me. After following the FB login guide I had a working prototype that would allow users to authenticate with FB. However this guide instructs you place all FB OAuth logic directly into the AppDelegate and that is not ideal for me since I will support more than just FB authentication. So what I have done is move the login logic into it's own class. Since then it seems that the FB delegate methods do not get called after a user successfully authenticates with FB and control should be passed back to my application.
I have a modal login view which takes my FacebookAuth class as a delegate. When I attempt to create a session the FB login page appears and I authorize my application. After that no other delegate methods are called. Can anyone provide some hints?
#interface FacebookAuth()
#property (nonatomic, strong) User *sessionUser;
#end
#implementation FacebookAuth
#synthesize sessionIsOpen = _sessionIsOpen;
#synthesize sessionUser = _sessionUser;
-(id)initWithViewDelegate:(id<AuthorizationViewDelegate>)viewDelegate
{
NSAssert(viewDelegate != nil, #"FacebookAuth must be initialized with a view delegate.");
self = [super init];
if (self) {
self.viewDelegate = viewDelegate;
}
return self;
}
-(id)init
{
self = [super init];
if (self) {
self = [self initWithViewDelegate:nil];
}
return self;
}
-(BOOL)sessionIsOpen{
return (FBSession.activeSession.state == FBSessionStateOpen);
}
-(void)requestSessionUserWithSuccess:(void (^)(User *))success Failure:(void (^)(NSError *))error{
if(!self.sessionIsOpen){
error([NSError errorWithDomain:#"Session Closed" code:0 userInfo:nil]);
return;
}
if(self.sessionUser == nil){
[[FBRequest requestForMe] startWithCompletionHandler:
^(FBRequestConnection *connection,
NSDictionary<FBGraphUser> *user,
NSError *err) {
if (!err) {
User *ses_user = [[User alloc]initWithId:user.id first:user.first_name last:user.last_name sessionToken: [[[FBSession activeSession] accessTokenData] accessToken]];
self.sessionUser = ses_user;
success(ses_user);
} else{
error(err);
}
}];
} else{
success(self.sessionUser);
}
}
-(void)openSession
{
[FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:YES
completionHandler:
^(FBSession *session,
FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
}];
}
-(void)closeSession{
[FBSession.activeSession closeAndClearTokenInformation];
self.sessionUser = nil;
self.sessionIsOpen = NO;
};
-(void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
switch (state) {
case FBSessionStateOpen:{
self.sessionIsOpen = YES;
[self.viewDelegate loginSuccess];
}
break;
case FBSessionStateClosed:{
self.sessionIsOpen = NO;
}
break;
case FBSessionStateClosedLoginFailed:{
[FBSession.activeSession closeAndClearTokenInformation];
self.sessionIsOpen = NO;
[self.viewDelegate loginFailure:error];
}
break;
default:
break;
}
}
-(BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
I apologize for the large code snippet but I don't want to leave out anything that may be valuable in assisting.
After calling
-(void)openSession:
The facebook authentication page appears and I authorize the application. After that I was expecting the FB delegate method to be called:
-(BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
It never is. Do I need to declare this class as a type of FB delegate? I am using the latest Facebook SDK available.
Any help would be great.

Resources