Search code examples
iosobjective-cfacebook-ios-sdk

Facebook SDK Objective-C trigger event after login


I'm new to IOS Application Development and this is the first time I've integrated the Facebook SDK into an application. I'm using my initial view controller to authenticate the user via the Facebook SDK and redirect him to another view controller once he is authenticated. Additionally, once he clicks on log out, I want to be able to redirect the user back to this initial view controller.

I'm using the following code (inside the viewDidLoad function) to add the Facebook login button to my view:

FBSDKLoginButton *loginButton = [[FBSDKLoginButton alloc] init];

// setting the facebook button position
float screenHeight = [[UIScreen mainScreen] bounds].size.height;
float screenWidth = [[UIScreen mainScreen] bounds].size.width;
CGPoint origin = CGPointMake(screenWidth/2, screenHeight - 100);

// Optional: Place the button in the center of your view.
loginButton.center = origin;
[self.view addSubview:loginButton];

The button is working fine, but I noticed that right after I login, the [FBSDKAccessToken currentAccessToken] is nil in all the view controller lifecycle functions. Basically, it seems that this value is initialised by the Facebook SDK after my page is loaded.

Is there any way to execute a function right after this access token gets initialised, so that I can successfully redirect to a different controller? or is there any functionality that might help me achieve this behaviour? Similarly, i'd like to be able to redirect the user back to this initial view controller once he clicks the logout button from a different view.


Solution

  • I found that, by far, the easiest solution to this problem would be setting View Controller as a delegate for the login button and implementing the following functions:

    First, you have to use this protocol:

    @interface LoginController ()<FBSDKLoginButtonDelegate>
    

    Then, set the view Controller as the button's delegate

    loginButton.delegate = self;
    

    Finally, you would have to make sure that the following 2 methods are implemented

    - (void)  loginButton:(FBSDKLoginButton *)loginButton
    didCompleteWithResult:(FBSDKLoginManagerLoginResult *)result
                    error:(NSError *)error{
       //use your custom code here
      //redirect after successful login 
    }
    - (void) loginButtonDidLogOut:(FBSDKLoginButton *)loginButton{
      //use your custom code here
      //redirect after successful logout 
    }