Problem:
Using the FB SDK and the method openActiveSessionWithReadPermissions, the completion handler doesn't appear to get called when the app is reopened from Facebook web or Facebook app and I get this error output:
FBSDKLog: FBSession INVALID transition from FBSessionStateCreated to FBSessionStateClosed
FBSDKLog: FBSession transition from FBSessionStateCreated to FBSessionStateCreatedOpening
Context
Using Facebook SDK 3.2.1
App is built for iOS 5.0+
Using xCode 4.6.1
Testing on Simulator iOS 5.1
Testing on iPhone 4S, running iOS 6.1.2 (not using 6.0 social framework as want to test implementation for 5.0+)
Updating an app that was originally built for iOS 3.0 and using an old version of sharekit, but has now been updated for ARC and the share kit implementation I believe has all been commented out - hoping the issue is not a conflict with a old share kit function, can't fin any within the code
Steps taken to resolve
Searched throughout Stack Overflow, found similar issues mentioned but not a solution
ios6 facebook integration login always FBSessionStateClosedLoginFailed never opens (i already have bool:application implemented)
Facebook iOS SDK 3.0 - session not open
Facebook SDK 3.1 - Error validating access token
Have the correct app bundle in the FB settings panel
Have the correct Facebook app ID is the plist
Have FB logging turned on FBSettings setLoggingBehavior
Specifics:
These are the steps I took to implement Facebook connectivity within the app.
The first step I took was walking through the Facebook tutorial at: https://developers.facebook.com/docs/tutorials/ios-sdk-tutorial/. I got the first part, the authentication part working as expected (I built a separate app as instructed by the tutorial.)
I then took the same steps within the tutorial in the app I'm updating, this did not work
I then followed the instructions on https://developers.facebook.com/docs/howtos/login-with-facebook-using-ios-sdk/ (which are very similar to the tutorial)
Again I ran into issues
Then spent a lot of time searching for solution, could not find one
Highlevel steps in code:
I have my FB methods set up in AppDelegate
In a specific view controller I have a button that calls the openSessionWithAllowLoginUI method to start the login process
Code
AppDelegate.m
- (void)applicationDidFinishLaunching:(UIApplication *)application
{
// set up facebook logging
[FBSettings setLoggingBehavior:[NSSet setWithObjects:FBLoggingBehaviorFBRequests, FBLoggingBehaviorFBURLConnections, FBLoggingBehaviorAccessTokens, FBLoggingBehaviorSessionStateTransitions, nil]];
// Call the ACAccountStore method renewCredentialsForAccount, which will update the OS's understanding of the token state
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){
}
}];
}
}
- (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).
NSLog(#"Calling app did become active");
[FBSession.activeSession handleDidBecomeActive];
}
/*
* Callback for session changes.
*/
- (void)sessionStateChanged:(FBSession *)session
state:(FBSessionState) state
error:(NSError *)error
{
NSLog(#"Session State Changed");
switch (state) {
case FBSessionStateOpen:
if (!error) {
// We have a valid session
NSLog(#"User session found");
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:
[FBSession.activeSession closeAndClearTokenInformation];
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];
}
}
/*
* Opens a Facebook session and optionally shows the login UX.
*/
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
NSLog(#"Openning session with Facebook");
return [FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
/*
* If we have a valid session at the time of openURL call, we handle
* Facebook transitions by passing the url argument to handleOpenURL
*/
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
// attempt to extract a token from the url
NSLog(#"Calling open URL");
return [FBSession.activeSession handleOpenURL:url];
}
- (void) closeSession {
NSLog(#"Clossing Facebook Sessions");
[FBSession.activeSession closeAndClearTokenInformation];
}
- (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url
{
NSLog(#"handleOpenUrl Called");
return [FBSession.activeSession handleOpenURL:url];
}
View Controller with button
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view from its nib.
// Register for Facebook change notification
[[NSNotificationCenter defaultCenter]
addObserver:self
selector:#selector(sessionStateChanged:)
name:FBSessionStateChangedNotification
object:nil];
}
- (IBAction)login:(id)sender {
ATIAppDelegate *myAppDelegate = (ATIAppDelegate *)[[UIApplication sharedApplication]delegate];
[myAppDelegate openSessionWithAllowLoginUI:YES];
}
What I think the issue could be?
It seems like it may be something with the tokens?
Or maybe the notification center?
Note that during testing I've been going and revoking access of the Facebook app to my account and then trying to login again to the app, I see these has caused issues with other users
Okay I figured it out - the issue was nothing to do with FB itself, the app (I'm working on updating someone else's code) had a setting in the .plist - 'Application does not run in background' set to true.
Meaning that once the app was relaunched from the Facebook app or Facebook mobile site it wasn't prepared to handle the next step.
If you don't want the app to run in the background, you can bind to the FBSDKApplicationDelegate in your AppDelegate like so:
import UIKit
import FBSDKLoginKit
#UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}
func applicationWillResignActive(_ application: UIApplication) {
FBSDKAppEvents.activateApp()
}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication: sourceApplication, annotation: annotation)
}
}
https://forums.developer.apple.com/thread/50332
http://ashishkakkad.com/tag/fbsdkapplicationdelegate/
Related
i'm adding Facebook and Google signup in my application but i have this issue
The operation couldn’t be completed. -10814
in the Facebook login and i don't know how to solve it, this is my app delegate code for the openUrl:
func application(_ application: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any])
-> Bool {
if let fbSDKAppId = FBSDKSettings.appID(), url.scheme!.hasPrefix("fb\(fbSDKAppId)"), url.host == "authorize" {
var shouldOpen :Bool = FBSDKApplicationDelegate.sharedInstance().application(application, open: url, sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as! String!,annotation:options[UIApplicationOpenURLOptionsKey.annotation])
return shouldOpen
}
else {
return GIDSignIn.sharedInstance().handle(url,
sourceApplication:options[UIApplicationOpenURLOptionsKey.sourceApplication] as? String,
annotation: [:])
}
}
what i can do?
now I used the latest SDK v4.26.0 downloaded from here and I followed the link for steps to install for FB. and my code is
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
if ([[[UIDevice currentDevice] systemVersion] floatValue] <= 9) {
// After iOS9 we can not use it anymore
login.loginBehavior = FBSDKLoginBehaviorSystemAccount;
} else {
login.loginBehavior = FBSDKLoginBehaviorWeb;
}
NSArray *permission = [[NSArray alloc] initWithObjects:#"email",#"public_profile",#"user_friends", nil];
NSLog( #"### running FB sdk version: %#", [FBSDKSettings sdkVersion] );
[login logInWithReadPermissions:permission fromViewController:(UIViewController *)self handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
[self removeActivityIndicatorWithBg:activityIndicator];
if (error) {
NSLog(#"Process error");
} else if (result.isCancelled) {
NSLog(#"Cancelled");
} else {
NSLog(#"Logged in%#",result.grantedPermissions);
}
}];
here i used the login behavior as FBSDKLoginBehaviorSystemAccount and I get the error as
(- error: "The operation couldn’t be completed. -10814)
so in my simulator or device contains no accounts setup in system settings for facebook. then it comes on the following block
if (error) {
NSLog(#"Process error");
}
if I print the error,
No Facebook account.
There are no Facebook accounts configured. You can add or create a Facebook account in Settings.
so I changed the loginBehavior from FBSDKLoginBehaviorSystemAccount to FBSDKLoginBehaviorWeb, I got all OP with out error
Worked after adding openUrl with options:
Facebook documentation
Note that application:openURL:options: is only available in iOS 9 and above. If you are building with an older version of the iOS SDK, you can use:
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
BOOL handled = [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation
];
// Add any custom logic here.
return handled;
}
LSApplicationQueriesSchemes property set in info.plist has solved the problem for me.
Check attached screenshot:
In this thread you can find an issue and a temporary fix for such kind of error.
FBSDKSharingDelegate callback is not working. I can post to facebook fine with the ios SDK, but I'd like to detect if the post was successful and take additional action to notify the user. However, the callback is not working for me. The delegate methods are not being called and I don't know why.
Using ios8, Parse as my backend. In Parse, the user is linked to FB. I'm using the IOS simulator.
What I've tried:
I've ensured that publish permissions are granted, saved, and linked to the Parse user. I've run a check and "publish_actions" are detected OK. The posting works fine as I can see the post on the facebook account. It's just the callback that is not working. I've checked my fb setup and it looks fine. For good measure at the very bottom I've included that relevant code from my app delegate. I've blocked out confidential keys with XXXX.
Code:
1st: See if user is logged in to Parse, if not, send to sign in and link to facebook account. Once that is done, I request "publish" permissions and link that additional permission to the Parse user. I know this works b/c when I recompile, it remembers the "publish" permissions and goes right to into the post.
#interface FacebookAPIPost () <FBSDKSharingDelegate>
#end
#implementation FacebookAPIPost
-(void)shareSegmentFacebookAPI { //if statement below
//1) logged in?, if not send to sign up screen
//2) else if logged in, link account to facebook account, then send post
//3) else send to post b/c signed up and linked already.
PFUser *currentUser = [PFUser currentUser];
if(!currentUser) {
[self pushToSignIn];
} else if(![PFFacebookUtils isLinkedWithUser:currentUser]){
[self linkUserToFacebook:currentUser];
NSLog(#"user account not linked to facebook");
} else {
[self shareSegmentWithFacebookComposer];
}
}
-(void)linkUserToFacebook:currentUser{
[PFFacebookUtils linkUserInBackground:currentUser withPublishPermissions:#[#"publish_actions"] block:^(BOOL succeeded, NSError *error) {
if(error){
NSLog(#"There was an issue linking your facebook account. Please try again.");
}
else {
NSLog(#"facebook account is linked");
//Send the facebook status update
[self shareSegmentWithFacebookComposer];
}
}];
}
-(void)shareSegmentWithFacebookComposer{
if ([[FBSDKAccessToken currentAccessToken] hasGranted:#"publish_actions"]) {
[self publishFBPost]; //publish
} else {
NSLog(#"no publish permissions"); // no publish permissions so get them, then post
[PFFacebookUtils linkUserInBackground:[PFUser currentUser]
withPublishPermissions:#[ #"publish_actions"]
block:^(BOOL succeeded, NSError *error) {
if (succeeded) {
NSLog(#"User now has read and publish permissions!");
[self publishFBPost];
}
}];
Here is where the post gets made:
-(void) publishFBPost{
FBSDKShareLinkContent *content = [FBSDKShareLinkContent new];
content.contentURL = [NSURL URLWithString:[self.selectedSegment valueForKey:#"linkToContent"]];
content.contentTitle = [self.selectedProgram valueForKey:#"programTitle"];
content.contentDescription = [self.selectedSegment valueForKey:#"purposeSummary"];
PFFile *theImage = [self.selectedSegment valueForKey:#"segmentImage"];
NSString *urlString = theImage.url;
NSURL *url = [NSURL URLWithString:urlString];
content.imageURL = url;
FBSDKShareDialog *shareDialog = [FBSDKShareDialog new];
[shareDialog setMode:FBSDKShareDialogModeAutomatic];
// [FBSDKShareDialog showFromViewController:self.messageTableViewController withContent:content delegate:self];
[shareDialog setShareContent:content];
[shareDialog setDelegate:self];
[shareDialog setFromViewController:self.messageTableViewController];
[shareDialog show];
}
Delegate methods below are not working. Meaning after the post is complete, I can see it on the FB account, but none of these delegate methods execute.
#pragma mark - delegate methods
- (void)sharer:(id<FBSDKSharing>)sharer didCompleteWithResults:(NSDictionary *)results {
// if ([sharer isEqual:self.shareDialog]) {
NSLog(#"I'm going to go crazy if this doesn't work.%#",results);
// Your delegate code
// }
}
- (void)sharer:(id<FBSDKSharing>)sharer didFailWithError:(NSError *)error
{
NSLog(#"sharing error:%#", error);
NSString *message = error.userInfo[FBSDKErrorLocalizedDescriptionKey] ?:
#"There was a problem sharing, please try again later.";
NSString *title = error.userInfo[FBSDKErrorLocalizedTitleKey] ?: #"Oops!";
[[[UIAlertView alloc] initWithTitle:title message:message delegate:nil cancelButtonTitle:#"OK" otherButtonTitles:nil] show];
}
- (void)sharerDidCancel:(id<FBSDKSharing>)sharer
{
NSLog(#"share cancelled");
}
Console output:
The only message I get back after posting is after a few seconds this message appears:
plugin com.apple.share.Facebook.post invalidated
Please help!
Footnote: appDelegate
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
// Initialize Parse.
[Parse enableLocalDatastore];
[Parse setApplicationId:#"XXXX"
clientKey:#"XXX"];
[PFFacebookUtils initializeFacebookWithApplicationLaunchOptions:launchOptions];
//Initialize Facebook
[FBSDKAppEvents activateApp];
return [[FBSDKApplicationDelegate sharedInstance] application:application didFinishLaunchingWithOptions:launchOptions];
}
//Method added for facebook integration
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
return [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
}
- (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.
[FBSDKAppEvents activateApp];
}
I think I am too late answering this question but someone else could trap into this as well, that's why sharing my knowledge.
As per Facebook API documentation
sharer:didCompleteWithResults: Sent to the delegate when the share completes without error or cancellation.
The results from the sharer. This may be nil or empty.
its probably because this delegate method is only get called when the post is successfully shared. In case of failure the other delegate method sharer:didFailWithError:get called. I think Facebook API should not need to add the result parameter is that case.
So in my experience if sharer:didCompleteWithResults whenever this is called that would mean success.
I have a little trouble when implementing new Facebook Login for our app. We are using Facebook SDK v4.3 for our development. And the login/signup process crashes on devices with low memory. We suspect that the low memory constraints have caused our app to terminate when it triggered a switch to Facebook for authentication. As document in the Facebook's old SDK (link https://developers.facebook.com/docs/facebook-login/ios#login-apicalls):
Login flows require an app switch to complete, it's possible your app gets terminated by iOS in low memory conditions or if your app does not support backgrounding.
In that case, the state change handler supplied to your open call disappears.
To handle that scenario explicitly assign a state change handler block to the FBSession instance any time prior to the handleOpenURL: call:
// During the Facebook login, your app passes control to the Facebook iOS app or Facebook in a mobile browser.
// After authentication, your app will be called back with the session information.
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation
{
// Note this handler block should be the exact same as the handler passed to any open calls.
[FBSession.activeSession setStateChangeHandler:^(FBSession *session, FBSessionState state, NSError *error) {
// Retrieve the app delegate
AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
// Call the app delegate's sessionStateChanged:state:error method to handle session state changes
[appDelegate sessionStateChanged:session state:state error:error];
}];
return [FBAppCall handleOpenURL:url sourceApplication:sourceApplication];
}
Unfortunately, the new Facebook SDK deprecated FBSession.activeSession and its stateChangeHandler. I followed the custom UI FBLogin button for my app, here is my appDelegate code
-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation{
return [[FBSDKApplicationDelegate sharedInstance] application:application
openURL:url
sourceApplication:sourceApplication
annotation:annotation];
}
The code works fine and executes perfectly under normal condition. However, it behave oddly under cold starts (due to low memory). So my question would be: How do we prevent this? Is there an equivalent handler for the new SDK?
PS. I did my job in managing the device's memory. But it still didn't work under this stressed conditions.
Edit: All I want is to grab the user's basic information on success. Therefore, I did not need keep track (or have the need to) of the access token. This is the block of code that I use to invoke login
FBSDKLoginManager *login = [[FBSDKLoginManager alloc] init];
[login logInWithReadPermissions:#[#"email"] handler:^(FBSDKLoginManagerLoginResult *result, NSError *error) {
if (error) {
[ErrorMessageDisplay displayErrorAlertOnViewController:self withTitle:FB_LOGIN_ERROR_TITLE andMessage:FB_LOGIN_ERROR_MESSAGE];
[self.loginView enableLoginButtons];
} else if (result.isCancelled) {
[ErrorMessageDisplay displayErrorAlertOnViewController:self withTitle:FB_LOGIN_CANCEL_TITLE andMessage:FB_LOGIN_CANCEL_MESSAGE];
[self.loginView enableLoginButtons];
} else {
[[[FBSDKGraphRequest alloc] initWithGraphPath:#"me" parameters:nil] startWithCompletionHandler:^(FBSDKGraphRequestConnection *connection, id user, NSError *error) {
//TODO do something in here
}];
}
}];
Using the part of the code, the app still freeze on low memory after authenticated using facebook. In fact, the handler did not get call at all
Make sure you follow all the steps in https://developers.facebook.com/docs/ios/getting-started including connecting the application:didFinishLaunchingWithOptions: of the FBSDKApplicationDelegate (in addition to the openURL:)
Check FBSDKAccessToken currentAccessToken in an appropriate area of your app (such as viewDidLoad, as described in https://developers.facebook.com/docs/facebook-login/ios/). This will be set for you by the SDK in cases of a "cold start" of your app.
I am trying to implement facebook login in my app, i have followed these two guides to the letter:
http://developers.facebook.com/docs/getting-started/facebook-sdk-for-ios/
https://developers.facebook.com/docs/howtos/login-with-facebook-using-ios-sdk/
But i get a linker error when i try to compile the app for iPhone emulator.
Undefined symbols for architecture i386:
"_FBSessionStateChangedNotification", referenced from:
-[AppDelegate sessionStateChanged:state:error:] in AppDelegate.o
-[LoginViewController viewDidLoad] in LoginViewController.o
-[AppDelegate sessionStateChanged:state:error:] in AppDelegate.o
-[LoginViewController viewDidLoad] in LoginViewController.o
ld: symbol(s) not found for architecture i386
I have made sure all the necessary frameworks and files is in the right place. Also, i get no code errors in Xcode, so i really don't know whats wrong here.
Please, any help is greatly appriciated.
EDIT:
//AppDelegate.h
#import <UIKit/UIKit.h>
#import <FacebookSDK/FacebookSDK.h>
#interface AppDelegate : UIResponder <UIApplicationDelegate> {
}
#property (strong, nonatomic) UIWindow *window;
extern NSString *const FBSessionStateChangedNotification;
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI;
- (void)closeSession;
#end
-
// AppDelegate.m
#import "AppDelegate.h"
#import "NetworkCheck.h"
#implementation AppDelegate
- (void)dealloc
{
[_window release];
[super dealloc];
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
// Override point for customization after application launch.
NSLog(#"Application launch");
NetworkCheck *netCheck = [[NetworkCheck alloc] init];
[netCheck startCheck];
NSString *const FBSessionStateChangedNotification = #"com.example.Login:FBSessionStateChangedNotification";
return YES;
}
/*
* If we have a valid session at the time of openURL call, we handle
* Facebook transitions by passing the url argument to handleOpenURL
*/
- (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];
}
/*
* Callback for session changes.
*/
- (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");
}
break;
case FBSessionStateClosed:
case FBSessionStateClosedLoginFailed:[FBSession.activeSession closeAndClearTokenInformation];
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];
}
}
/*
* Opens a Facebook session and optionally shows the login UX.
*/
- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI {
return [FBSession openActiveSessionWithReadPermissions:nil
allowLoginUI:allowLoginUI
completionHandler:^(FBSession *session,
FBSessionState state,
NSError *error) {
[self sessionStateChanged:session
state:state
error:error];
}];
}
- (void) closeSession {
[FBSession.activeSession closeAndClearTokenInformation];
}
- (void)applicationWillResignActive:(UIApplication *)application
{
// Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
// Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
}
- (void)applicationDidEnterBackground:(UIApplication *)application
{
// Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
// If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
}
- (void)applicationWillEnterForeground:(UIApplication *)application
{
// Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
}
- (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.
// 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];
}
- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
[FBSession.activeSession close];
}
#end
FBSessionStateChangedNotification is an extern definition that's supposed to be visible within any header file you're importing in order to be accessible to the code you write in your appDelegate.
You need to transfer this line:
NSString *const FBSessionStateChangedNotification = #"com.example.Login:FBSessionStateChangedNotification";
To a file that will make it visible for other classes (not only the app delegate).
i am integrating login through facebook in an ios app , in which during the app launch i show an alert to the user , and when the user clicks on the OK button on the alert view , then the FB login dialog is shown to the user .The problem is when i click on the home button and relaunch the app to show the alert, then after clicking on OK does not show the user the facebook login dialog. i have used the facebook ios sdk 3.0 and xcode 4.5 gm. *Interestingly when i kill the app from background every thing works fine.*below is the code in the app did finish launching for facebook
if (!self.session.isOpen)
{
NSArray *permissions = [[NSArray alloc] initWithObjects:
#"user_likes",
#"read_stream",#"publish_stream",#"email",
nil];
self.session = [[FBSession alloc] initWithPermissions:permissions];
if (self.session.state == FBSessionStateCreatedTokenLoaded)
{
// even though we had a cached token, we need to login to make the session usable
[self.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
}];
}
}
this is the method i call when user clicks on the OK button on the alert view
-(IBAction) facebookLogin
{
if (self.session.isOpen)
{
[self.session closeAndClearTokenInformation];
}
else
{
if (self.session.state != FBSessionStateCreated) {
// Create a new, logged out session.
self.session = [[FBSession alloc] init];
}
[self.session openWithCompletionHandler:^(FBSession *session,
FBSessionState status,
NSError *error) {
if (error) {
NSLog(#"dex is %#",error.description);
}
}];
}
}
Follow this doc on Facebook developer.
It explains how to handle login and logout functionalities. Implement as it says, works perfectly. And also you can use the latest 3.1 sdk.
It's an old question, but anyway.
I had same behaviour when I didn't updated my AppDelegate. In swift it should look like this:
func application(application: UIApplication, openURL url: NSURL, sourceApplication: String?, annotation: AnyObject) -> Bool {
return FBSDKApplicationDelegate.sharedInstance().application(application, openURL: url, sourceApplication: sourceApplication, annotation: annotation)
}
func applicationWillResignActive(application: UIApplication) {
FBSDKAppEvents.activateApp()
}
func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
// Some code was here
return FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions)
}