Search code examples
iosxcodefacebookswiftfacebook-ios-sdk

Facebook SDK for iOS handle login


I'm using the Facebook SDK for iOS together with the parse.com SDK for my backend (but that's not important for my problem).

Both SDK's are working properly.

When the user opens my app for the first time (as long as he isn't logged in), a modal view controller appears which says "you're not logged in blah blah" and the Facebook login button provided by the SDK.

When the user tappes the login button, the Facebook app (or Safari) opens and you can login with Facebook, then you return to my app and you are logged in. That also works fine.

So, when the user is now logged in or he opens the app on the next day for example, how can I check if he is logged in? I want to fetch the whole news feed of the logged in user to be shown.

If I'm using

FBSession.activeSession().isOpen

it's always false, because at the time I want to know that, the session isn't active. Is there any notification or event-handler to be able to get to know when the session gets active?

That's what I want:

  • When the user opens the app (he is logged in) the view controller should say something like 'logging in to facebook and loading your news feed..'
  • when logged in successfully, the view should show the latest e.g. 20 posts from the users' news feed
  • when the user isn't logged in, I want to show my modal view controller with the Facebook login button

I read the documentation of the Facebook SDK and searched a lot on Google, but nothing answered my question. I just want to know how to handle that damn Facebook login.

Please help me!


Solution

  • When the app loads, the FB SDK does not load anything on its own. You can prompt it to check if the user is still connected to your app without bringing up the login dialog.

    For FB SDK v3.x:

    if (!FBSession.activeSession.isOpen) {
        BOOL isLoggedIn = [FBSession openActiveSessionWithAllowLoginUI:NO];
    }
    

    FB SDK 4.x now checks on its own as long as you add the appropriate lines to your app delegate from their documentation.

    BOOL isLoggedIn = NO;
    if ([FBSDKAccessToken currentAccessToken]) {
        isLoggedIn = YES;
        NSLog(@"facebook already connected");
    }
    

    Ideally, you should track whether or not the user has previously logged in by saving some information (eg their FB id) into NSUserDefaults, in my opinion, rather than relying on Facebook's SDK for that, but this should work.