Saving Facebook access_token in NSUserDefaults on iOS

这一生的挚爱 提交于 2019-12-12 02:08:52

问题


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 standardUserDefaults];
    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?


回答1:


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.



来源:https://stackoverflow.com/questions/6025180/saving-facebook-access-token-in-nsuserdefaults-on-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!