开发者

Saving Facebook access_token in NSUserDefaults on iOS

开发者 https://www.devze.com 2023-03-06 03:50 出处:网络
iOS beginner here. I\'m using the following code to save my facebook accessToken and expirationDate in NSUserDefaults:

iOS beginner here. I'm using the following code to save my facebook accessToken and expirationDate in NSUserDefaults:

facebook = [[Facebook alloc] initWithAppId:@"225083222506272"];
    [facebook authorize:nil delegate:self];
    NSString *access=[facebook accessToken];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSDictionary *appDefaults = [NSDictionary dictionaryWithObjectsAndKeys:access, @"accessToken",[facebook expirationDate], @"expirationDate",nil];
    [defaults registerDefaults:appDefaults];

And I'm trying to retrieve accessToken and expirationDate in a later call with:

 NSUserDefaults *defaults = [NSUserDefaults standardU开发者_开发知识库serDefaults];
    NSString *access=[defaults valueForKey:@"accessToken"];
    NSDate *date=[defaults objectForKey:@"expirationDate"];
    [facebook fbDialogLogin:access expirationDate:date];

but access and date are null. What am I doing wrong?


The code here is not synchronous. It means it does not block after the call to [facebook authorize:nil delegate:self];. You should instead implement the fbDidLogin delegate method to be notified of when the user has actually logged in successfully. At that point, retrieve the access tokens and save them to user defaults.

Here's a partial sample:

- (void)userClickedFacebookLogin {
    [facebook authorize:nil delegate:self]; // delegate is self
}

// Delegate method that you should implement to get notified
// when user actualy logs in.
- (void)fbDidLogin {
    // now get the access token and save to user defaults
    NSString *access = [facebook accessToken];
    // ..
}

Also make sure that the class which has the above code implements the FBSessionDelegate protocol at minimum.

@interface MyClass <FBSessionDelegate> {

}

@end

Look at the DemoApp sample and specifically the DemoAppViewController class from Facebook to get a better idea.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号