Stay logged in between application launches

12 Feb

In the old version of Facebook iOS SDK to stay logged in next time your application launches you would call [session resume].

You will notice that new Facebook SDK for iPhone is lacking this functionality.

Here is an example of how you achieve same results in the new version of SDK.

Save access token and expiration date on successful login event:

- (void)fbDidLogin {
	NSLog(@"logged in");
        [[NSUserDefaults standardUserDefaults] setObject:_facebook.accessToken forKey:@"AccessToken"];
	[[NSUserDefaults standardUserDefaults] setObject:_facebook.expirationDate forKey:@"ExpirationDate"];

When the view is loaded set access token and expiration date to their saved values. Is session is still valid, Facebook will not ask the user to login again.

- (void)viewDidLoad {
        _facebook = [[Facebook alloc] initWithAppId:kAppId];
	_facebook.accessToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"AccessToken"];
	_facebook.expirationDate = [[NSUserDefaults standardUserDefaults] objectForKey:@"ExpirationDate"];
	[_facebook authorize:_permissions delegate:self];

        // or do not show dialog at all
        if ([_facebook isSessionValid]) {
		// your code
	else {
		[_facebook authorize:_permissions delegate:self];

Posted by on February 12, 2011 in Apple, Facebook


4 responses to “Stay logged in between application launches

  1. Ally

    February 21, 2011 at 4:40 pm

    While I’m doing this, my tokens only last for 24 hours, so I’m asking users to log in again every day. Any better options than just asking for the offline_access permission? It seems a little heavy-handed…

    • Dasha

      February 22, 2011 at 7:46 pm

      Ally, thanks for comment. I am trying to find a solution for this issue myself. Please let me know if you find it before me.

  2. Emmanuel Ay

    July 4, 2011 at 9:58 am

    Hey there!
    Heres a solution & a fix:

    1. Add this to your fbDidLogin method:
    [[NSUserDefaults standardUserDefaults] synchronize];
    ..otherwise the credentials wont be persisted.

    2. When you load the access token and the expiration date, make sure to set the expiration date to something distant, like this:
    _facebook.expirationDate = [NSDate distantFuture];
    That should solve the expiration problem.

    • Dasha Salo

      July 4, 2011 at 10:01 am

      Cool! Will try it out. Thank you!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: