Saving Facebook access_token in NSUserDefaults on iOS
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.
精彩评论