0
- (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,不等待块完成。应该改变什么?

4

1 回答 1

2

这是一个异步调用,因此该块在您的方法结束后完成。你需要重新设计你的应用程序来完成它在完成块中必须做的事情。如果它不是 nil,你打电话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);
        }
    }];
}
于 2012-09-20T17:00:28.120 回答