我的应用仅限iOS7,为了避免头痛,我决定不使用Facebook SDK进行身份验证,而是依赖iOS的ACAccountStore。不幸的是,我仍然感到头痛。
我有一个名为FacebookService的类,其中一个方法名为login
。我将在下面发布代码,但一般情况下,我会执行配置ACAccountStore
实例的标准舞蹈,然后调用requestAccessToAccountsWithType
。在完成块中,如果granted
返回false,则向用户发送消息并发送短路。
如果granted
为真,那么我的代码用于假设我拥有使用以下代码获取用户的oauthToken所需的一切:
ACAccount *fbAccount = [[accountStore accountsWithAccountType:fbAccountType] lastObject];
ACAccountCredential *fbCredential = [fbAccount credential];
NSString *accessToken = [fbCredential oauthToken];
我从oauthToken
获得了ACAccount#credential
,而第一件奇怪的事情是according to the documentation:
出于隐私原因,此属性(保存帐户后无法访问。
我可以肯定地告诉你,大多数时候,这个属性是绝对可访问的,我可以使用它发送到我的服务器找到以前认证的用户。
然而,有几次,该值实际上将为空。并且在发生这种情况的每种情况下,如果用户转到设置>则可以解决该问题。 Facebook>关闭我们的应用>打开我们的应用程序。他们回到我们的应用程序,点击“使用Facebook登录”,一切正常。
所以这是我的问题:
这是我的代码:
- (void)login
{
ACAccountStore *accountStore = [[ACAccountStore alloc] init];
ACAccountType *fbAccountType = [accountStore accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSString *appId = [[Environment sharedInstance] fbAppId];
NSDictionary *fbOptions = @{
ACFacebookAppIdKey : appId,
ACFacebookPermissionsKey : [@"email,user_birthday,user_hometown,user_location,user_photos" componentsSeparatedByString:@","],
ACFacebookAudienceKey: ACFacebookAudienceEveryone
};
[accountStore requestAccessToAccountsWithType:fbAccountType options:fbOptions completion:^(BOOL granted, NSError *error) {
NSString *message;
NSString *title;
if (!granted) {
if (!error || error.code == ACErrorPermissionDenied) {
title = @"AFAR Needs Your Permission";
message = @"Your Facebook account is configured in Settings. Go to Settings and enable AFAR.";
} else if (error.code == ACErrorAccountNotFound) {
title = @"No Facebook Account";
message = @"There are no Facebook accounts configured. You can add or create a Facebook account in Settings.";
}
if (message) {
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AfarFacebookLoginDidNotSucceed object:nil];
[UIAlertView simpleAlertWithTitle:title message:message];
});
}
return;
}
ACAccount *fbAccount = [[accountStore accountsWithAccountType:fbAccountType] lastObject];
ACAccountCredential *fbCredential = [fbAccount credential];
NSString *accessToken = [fbCredential oauthToken];
if ([accessToken isEmpty]) {
message = @"You need to allow AFAR access to your Facebook account. Please visit Settings > Facebook and look for the AFAR entry. Turn the AFAR setting off, then back on.";
title = @"Problem Connecting to Facebook";
dispatch_async(dispatch_get_main_queue(), ^{
[[NSNotificationCenter defaultCenter] postNotificationName:AfarFacebookLoginDidNotSucceed object:nil];
[UIAlertView simpleAlertWithTitle:title message:message];
});
return;
}
[SessionAPIService signInUsingFacebookToken:accessToken withBlock:^(NSError *error) {
if (!error) {
[[NSNotificationCenter defaultCenter] postNotificationName:AFARCurrentUserDidSignInNotificatioName object:nil];
}
}];
}];
}