在iOS上的NSUserDefaults中保存Facebook access_token [英] Saving Facebook access_token in NSUserDefaults on iOS

查看:189
本文介绍了在iOS上的NSUserDefaults中保存Facebook access_token的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

iOS初学者在这里。我正在使用以下代码将我的facebook accessToken和expirationDate保存在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];

我在以后的调用中试图检索accessToken和expirationDate:

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?

推荐答案

此处的代码不同步。这意味着它不会在调用 [facebook authorize:nil委托:self]; 之后阻塞。相反,您应该实现 fbDidLogin 委托方法,以在用户实际成功登录时收到通知。此时,获取访问令牌并将其保存为用户默认值。

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.

这里是部分示例:

- (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];
    // ..
}

还请确保具有上面的代码至少实现了 FBSessionDelegate 协议。

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

@interface MyClass <FBSessionDelegate> {

}

@end

看在 DemoApp 示例,尤其是来自Facebook的 DemoAppViewController 类,以获得更好的主意。

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

这篇关于在iOS上的NSUserDefaults中保存Facebook access_token的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆