【问题标题】:Check when multiple asynchronous network operations are completed检查多个异步网络操作何时完成
【发布时间】:2013-05-27 00:55:51
【问题描述】:

我的应用程序从 Flickr 上的用户那里下载了大量信息和图像,我使用 AFHttpClient。所以基本上,每个人都会异步执行一个有效的NSUrlConnection,然后运行一个完成块。一个类对每个api调用都有方法,另一个类通过api调用循环获取每个用户的数据,这些数据放入核心数据中。但是,我的问题是我无法为调用 api 类的类找到一种方法来确定所有下载何时完成并将其放入核心数据中。此外,我将同时下载多个用户数据,并且根据用户的不同,不同的属性以不同的顺序完成加载。有什么建议吗?

【问题讨论】:

  • 您找到任何解决方案了吗?请发一些。

标签: ios objective-c networking asynchronous afnetworking


【解决方案1】:

AFNetworking 让管理多个请求和最终回调变得非常简单,只需使用:

- (void)enqueueBatchOfHTTPRequestOperations:(NSArray *)operations 
                          progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock 
                        completionBlock:(void (^)(NSArray *operations))completionBlock;

- (void)enqueueBatchOfHTTPRequestOperationsWithRequests:(NSArray *)urlRequests
                                      progressBlock:(void (^)(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations))progressBlock 
                                    completionBlock:(void (^)(NSArray *operations))completionBlock;

在 AFHHTPClient 实例上。

示例:

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]];
NSURLRequest *otherRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:@""]];

AFHTTPRequestOperation *operationForImages = [[AFHTTPRequestOperation alloc] initWithRequest:request];
[operationForImages setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    //success of images request
    self.imageDictionary = responseObject;

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    //manage error for this request

}];
AFHTTPRequestOperation *operationForText = [[AFHTTPRequestOperation alloc] initWithRequest:otherRequest];
[operationForText setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) {

    //success of text request
    self.textDictionary = responseObject;

} failure:^(AFHTTPRequestOperation *operation, NSError *error) {

    //manage error for this request

}];


[[MyPersonalAFHTTPClient sharedClient] enqueueBatchOfHTTPRequestOperations:@[operationForImages,operationForText] progressBlock:^(NSUInteger numberOfFinishedOperations, NSUInteger totalNumberOfOperations) {

    //track progression of requests

} completionBlock:^(NSArray *operations) {

    //all the request are completed

}];

【讨论】:

    【解决方案2】:

    使用实例变量记录正在进行的活动请求的数量。这可以是一个简单的 NSInteger 递增和递减,或者它可以是一个字典,由用户名键入,并在需要时保存一个数字或更详细的跟踪记录。这真的取决于你需要什么级别的细节。进行 API 调用的类应该对这些记录数据进行所有管理,并且只提供“计数”方法。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多