Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8468973
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 10, 20262026-06-10T16:05:48+00:00 2026-06-10T16:05:48+00:00

I’ve been following one of the Login tutorials from the Facebook SDK. I have

  • 0

I’ve been following one of the Login tutorials from the Facebook SDK. I have coded this correctly to log in and log out using the same ViewController and Button. I was wondering how to activate another ViewController once logged in to Facebook, any advice would be great…

I have a LoginViewController and once logged in I want to launch MainViewController

Code:

AppDelegate.h

#import <UIKit/UIKit.h>
#import <FacebookSDK/FacebookSDK.h>

@interface AppDelegate : UIResponder <UIApplicationDelegate>

@property (strong, nonatomic) UIWindow *window;

extern NSString *const FBSessionStateChangedNotification;
extern NSString *const SCSessionStateChangedNotification;

- (BOOL)openSessionWithAllowLoginUI:(BOOL)allowLoginUI;

- (void) closeSession;

@end

AppDelegate.m

#import "AppDelegate.h"

@implementation AppDelegate

NSString *const FBSessionStateChangedNotification =
@"com.example.Login:FBSessionStateChangedNotification";

NSString *const SCSessionStateChangedNotification =
@"com.nathancleary.Login:SCSessionStateChangedNotification";

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:  (NSDictionary *)launchOptions
{
// Override point for customization after application launch.
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];
}

- (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.

// this means the user switched back to this app without completing
// a login in Safari/Facebook App
if (FBSession.activeSession.state == FBSessionStateCreatedOpening) {
    [FBSession.activeSession close]; // so we close our session and start over
}
}

- (void)applicationWillTerminate:(UIApplication *)application
{
// Called when the application is about to terminate. Save data if appropriate. See also   applicationDidEnterBackground:.

[FBSession.activeSession close];
}

/*
* 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 {
NSArray *permissions = [[NSArray alloc] initWithObjects:
                        @"user_likes",
                        @"read_stream",
                        nil];
return [FBSession openActiveSessionWithPermissions:permissions
                                      allowLoginUI:allowLoginUI
                                 completionHandler:^(FBSession *session,
                                                     FBSessionState state,
                                                     NSError *error) {
                                     [self sessionStateChanged:session
                                                         state:state
                                                         error:error];
                                 }];
}

- (void) closeSession {
[FBSession.activeSession closeAndClearTokenInformation];
}

@end

LoginViewController.h

#import <UIKit/UIKit.h>

@interface LoginViewController : UIViewController

- (IBAction)authButtonAction:(id)sender;

@property (strong, nonatomic) IBOutlet UIButton *authButton;

@end

LoginViewController.m

#import "LoginViewController.h"
#import "AppDelegate.h"

@interface LoginViewController ()

@end

@implementation LoginViewController
@synthesize authButton;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
    // Custom initialization
}
return self;
}

- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view.

[[NSNotificationCenter defaultCenter]
 addObserver:self
 selector:@selector(sessionStateChanged:)
 name:FBSessionStateChangedNotification
 object:nil];

// Check the session for a cached token to show the proper authenticated
// UI. However, since this is not user intitiated, do not show the login UX.
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
[appDelegate openSessionWithAllowLoginUI:NO];
}

- (void)viewDidUnload
{
[self setAuthButton:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.

[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)sessionStateChanged:(NSNotification*)notification {
if (FBSession.activeSession.isOpen) {
    [self.authButton setTitle:@"Logout" forState:UIControlStateNormal];
} else {
    [self.authButton setTitle:@"Login" forState:UIControlStateNormal];
}
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (IBAction)authButtonAction:(id)sender {

AppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];

// If the user is authenticated, log out when the button is clicked.
// If the user is not authenticated, log in when the button is clicked.
if (FBSession.activeSession.isOpen) {
    [appDelegate closeSession];
} else {
    // The user has initiated a login, so call the openSession method
    // and show the login UX if necessary.
    [appDelegate openSessionWithAllowLoginUI:YES];
}


}

@end
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-10T16:05:49+00:00Added an answer on June 10, 2026 at 4:05 pm

    If you are using Facebook’s sdk 3 you can place this in the method called by the completition handler:

    - (void)openFacebookSession
    {
        NSArray *permissions = [[NSArray alloc] initWithObjects:
                                @"user_photos",
                                nil];
        [FBSession openActiveSessionWithPermissions:permissions
                                       allowLoginUI:YES
                                  completionHandler: ^(FBSession *session, FBSessionState state, NSError *error){
                                      [self sessionStateChanged:session state:state error:error];
                                  }];
    }
    

    Here is where the main viewcontroller is launched:

    - (void)sessionStateChanged:(FBSession *)session
                          state:(FBSessionState) state
                          error:(NSError *)error
    {
        switch (state) {
            case FBSessionStateOpen:
            {
                NSLog(@"FBSessionStateOpen");
    
                //[activityIndicator startAnimating];
                // initialize the viewcontroller with a little delay, so that the UI displays the changes made above
                double delayInSeconds = 0.1;
                dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, delayInSeconds * NSEC_PER_SEC);
                dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
    
                    UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"MainStoryboard"
                                                                             bundle: nil];
    
                    UIViewController *controller = [mainStoryboard instantiateViewControllerWithIdentifier: @"MainViewController"];
    
                    [self presentViewController:controller animated:YES completion:nil];
    
                    //[activityIndicator stopAnimating];
                });
    
                break;
            }
    
            case FBSessionStateClosed:
            {
                NSLog(@"FBSessionStateClosed");
                break;
            }
    
            case FBSessionStateClosedLoginFailed:
            {
                 [FBSession.activeSession closeAndClearTokenInformation];
                 NSLog(@"Facebook State Closed or Failed");
    
                 break;
            }
            default:
            {
                 break;
            }
        }
    
        if (error) {
            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Error"
                                                                message:error.localizedDescription
                                                               delegate:nil
                                                      cancelButtonTitle:@"OK"
                                                      otherButtonTitles:nil];
            [alertView show];
        }
    }
    

    THIS method is specifically made for when you have to load a heavy main controller (thats why you can activate a loading indicator). You can easily modify it to load a simple one which can be initiated in the same thread.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I have a string like this: La Torre Eiffel paragonata all&#8217;Everest What PHP function
I have a jquery bug and I've been looking for hours now, I can't
For some reason, after submitting a string like this Jack’s Spindle from a text
this is what i have right now Drawing an RSS feed into the php,
I have this code to decode numeric html entities to the UTF8 equivalent character.
This could be a duplicate question, but I have no idea what search terms
I'm parsing an RSS feed that has an &#8217; in it. SimpleXML turns this
I have this code: - (void)parser:(NSXMLParser *)parser foundCDATA:(NSData *)CDATABlock { NSString *someString = [[NSString
I have a text area in my form which accepts all possible characters from
I know there's a lot of other questions out there that deal with this

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.