- (ACAccount *)accountFacebook{
if (_accountFacebook) {
return _accountFacebook;
}
if (!_accountStoreFacebook) {
_accountStoreFacebook = ACAccountStore.new;
}
ACAccountType *accountTypeFacebook = [self.accountStoreFacebook accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSDictionary *options = @{ACFacebookAppIdKey : @"xxxxxxxxx",
ACFacebookAudienceKey : ACFacebookAudienceEveryone,
ACFacebookPermissionsKey : @[@"user_about_me", @"publish_actions"]
};
__block ACAccount *accountFb;
[_accountStoreFacebook requestAccessToAccountsWithType:accountTypeFacebook options:options completion:^(BOOL granted, NSError *error) {
if (granted) {
NSLog(@"Facebook access granted");
accountFb = _accountStoreFacebook.accounts.lastObject;
}else {
NSLog(@"Facebook access denied");
accountFb = nil;}
if (error) {
NSLog(error.localizedDescription);
}
}];
return accountFb;
}
当我跑步时
AppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
if (appDelegate.accountFacebook) {
NSLog(@"accountFacebook OK");
}else NSLog(@"accountFacebook Not Exists");
appDelegate.accountFacebook总是返回nil,不等待块完成。 应该改变什么?
答案 0 :(得分:2)
这是一个异步调用,因此块在方法结束后完成。您需要重新设计应用程序,以便在完成块中执行必须执行的操作。你打电话给appDelegate.accountFacebook
并期望做一些事情,如果它不是零。为什么不将这个方法传递给一个完成块,它将执行你想要它执行的操作,如下所示:
typedef void(^HandlerType)(ACAccount* account);
- (void)performForFacebookAccount: (HandlerType) handler{
if (_accountFacebook) {
handler(_accountFacebook);
return;
}
if (!_accountStoreFacebook) {
_accountStoreFacebook = ACAccountStore.new;
}
ACAccountType *accountTypeFacebook = [self.accountStoreFacebook accountTypeWithAccountTypeIdentifier:ACAccountTypeIdentifierFacebook];
NSDictionary *options = @{ACFacebookAppIdKey : @"xxxxxxxxx",
ACFacebookAudienceKey : ACFacebookAudienceEveryone,
ACFacebookPermissionsKey : @[@"user_about_me", @"publish_actions"]
};
[_accountStoreFacebook requestAccessToAccountsWithType:accountTypeFacebook options:options completion:^(BOOL granted, NSError *error) {
if (granted) {
NSLog(@"Facebook access granted");
_accountFacebook = _accountStoreFacebook.accounts.lastObject;
handler(_accountFacebook);
}else {
NSLog(@"Facebook access denied");
_accountFacebook = nil;}
if (error) {
NSLog(error.localizedDescription);
}
}];
}