如果用户登录本地Facebook,是否有办法通过FBSession使用Facebook SDK获取缓存访问令牌。
我正在尝试通过Facebook在应用程序中实现自动登录,即当用户登录本地Facebook时,应用程序不应该要求登录,用户应该自动登录。
我使用了FBSession和FBTokenCacheStrategy并且用户自动登录但我无法获取我需要调用某些API的访问令牌。我用以下代码来完成这项工作:
CacheToken = [[FBTokenCache alloc]init];
NSArray *permissions = [[NSArray alloc]initWithObjects:@"email,user_photos,user_videos,publish_stream,offline_access,user_checkins,friends_checkins", nil];
self.fbsession = [[FBSession alloc] initWithAppID:@"484473011575776"
permissions:permissions
urlSchemeSuffix:nil
tokenCacheStrategy:CacheToken];
(fbsession is the object of Facebook SDK class FBSession)
[FBSession setActiveSession:self.fbsession];
[FBSession openActiveSessionWithReadPermissions:permissions
allowLoginUI:YES
completionHandler:^(FBSession *session, FBSessionState state, NSError *error) {
[self sessionStateChanged:session state:state error:error];
提前致谢。
答案 0 :(得分:3)
要获取访问令牌,您应该使用:
[FBSession activeSession] accessToken]
但是,您似乎想要检查是否已存在(缓存)访问令牌。要做到这一点,你可以这样做:
// See if we have a valid token for the current state.
if (FBSession.activeSession.state == FBSessionStateCreatedTokenLoaded) {
NSLog(@"The value access token is: %@", [[FBSession activeSession] accessToken]);
} else {
// No, display the login page.
}
请务必在您的app delegate中执行此操作,否则访问令牌将为nil:
- (BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
{
return [FBSession.activeSession handleOpenURL:url];
}
- (void)applicationDidBecomeActive:(UIApplication *)application
{
// We need to properly handle activation of the application with regards to Facebook Login
// (e.g., returning from iOS 6.0 Login Dialog or from fast app switching).
[FBSession.activeSession handleDidBecomeActive];
}
希望这有帮助
答案 1 :(得分:2)
尝试以下代码..
if (FBSession.activeSession.isOpen)
{
NSString *token = [[[FBSession activeSession] accessTokenData] accessToken];
}
希望这对你有用..