加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ios – 使用FacebookSDK从异步块返回值的方法

发布时间:2020-12-15 01:43:02 所属栏目:百科 来源:网络整理
导读:我想要做的是Facebook iOS SDK的Facebook包装.基本上我的想法是我的ViewController除了显示ex之外什么都不做.我的朋友将通过简单的电话获得 self.friends = [FacebookWrapper myFriends];[self.tableView reloadData]; 我的包装器myFriends方法看起来应该是
我想要做的是Facebook iOS SDK的Facebook包装.基本上我的想法是我的ViewController除了显示ex之外什么都不做.我的朋友将通过简单的电话获得

self.friends = [FacebookWrapper myFriends];
[self.tableView reloadData];

我的包装器myFriends方法看起来应该是这样的

+ (NSArray *)myFriends
{
   __block NSArray *friends = nil;
   [FBSession openActiveSessionWithReadPermissions:nil allowLoginUI:YES completionHandler:^(FBSession *session,FBSessionState status,NSError *error) {
    if(FB_ISSESSIONOPENWITHSTATE(status)) {
    [FBRequestConnection startForMyFriendsWithCompletionHandler:^(FBRequestConnection *connection,id data,NSError *error) {
       CFRunLoopStop(CFRunLoopGetCurrent());
        if(error) {
            return;
        }
        NSArray *friendsData = (NSArray *)[data data];
        NSMutableArray *fbFriends = [NSMutableArray array];
        for(id friendData in friendsData) {
            Friend *friend = [Friend friendWithDictionary:friendData];
            fbFriends addObject:friend];
        }
        friends = [NSArray arrayWithArray:fbFriends];
    }];
    CFRunLoopRun();
    }
  }];
  return friends;
}

问题是openActiveSessionWithReadPermissions和startForMyFriendsWithCompletionHandler是异步块,因此该方法在块完成其任务之前返回.

任何帮助将非常感激.

解决方法

我在过去创建了一个类似的包装器,我的方法是在调用我的包装器方法时传递一个“完成块”;一旦所有异步调用都完成运行,就会触发此完成块,并且它会接收您的方法在同步方案中返回的任何数据(在您的情况下,是朋友数组).

为了说明 – 您可以将“myFriends”方法重新定义为:

??(void)myFriendsWithCompletionBlock:(void(^)(NSArray * friends))completionBlock;

然后在执行中,在friends = [NSArray arrayWithArray:fbFriends]之后;你会加上这个:

if (completionBlock != nil) {
    completionBlock(friends);
}

…并在结尾处删除return语句.

最后,在您的视图控制器(或使用该方法的任何对象)上,您将执行以下操作:

[FacebookWrapper myFriendsWithCompletionBlock:^(NSArray *friends){
    // do what you need to do with the friends array
}];

当然,这仍然是异步的 – 但是没有办法解决Facebook SDK的构建方式(而且,公平地说,这可能是最好的方法 – 等待完成同步的请求会很糟糕!)

编辑:我注意到你也从包装器方法返回,以防它失败;在那种情况下,而不是返回你会做这样的事情:

if (completionBlock != nil) {
    completionBlock(nil);
}

这将导致在调用完成块时,friends数组为nil – 然后您可以在那里处理该错误,但这对您来说是合适的.

希望这有帮助!

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读