4

我首先使用 AFHTTPClient 下载单个索引文档,并使用 CoreData 记录每条记录。然后我需要启动一个单独的进程来下载每个单独的记录。最好的方法是什么?

对每个资源提出请求并让它们完成是否合理?可能有一百个左右。

或者,我可以先加载,提交请求,然后成功加载并提交后续请求。

我正在使用 CoreData 更新数据库,我认为这意味着我需要为每个请求提供一个单独的 NSManagedObjectContent ?

我也很想知道,AFHTTPClient 是在主线程上执行回调,还是在发起请求的线程上执行回调?我宁愿不阻止主线程执行 CoreData I/O。

4

1 回答 1

2

关于下载资源,您可以使用 AFNetworking 对它们进行排队。

您也许可以使用 - (void)enqueueHTTPRequestOperation:(AFHTTPRequestOperation *) AFHTTPClient 的操作。

首先创建一个单例来保存你自己的 AFHTTPClient ,如下所示:

@interface CustomHTTPClient : NSObject

+ (AFHTTPClient *)sharedHTTPClient;

@end


@implementation CustomHTTPClient

+(AFHTTPClient *)sharedHTTPClient {

  static AFHTTPClient *sharedHTTPClient = nil;

  if(sharedHTTPClient == nil) {
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{

    // Create the http client
    sharedHTTPClient = [AFHTTPClient clientWithBaseURL:[NSURL URLWithString:@"http://mybaseurl.com"]];

    });
  }

  return sharedHTTPClient;
}

@end

然后像这样排队您的请求:

// Store the operations in case the failure block needs to cancel them
__block NSMutableArray *operations = [NSMutableArray array];

// Add operations for url
for (NSURL *url in urls) {

  NSURLRequest *request = [NSURLRequest requestWithURL:url];

  __block AFHTTPRequestOperation *operation = [[CustomHTTPClient sharedHTTPClient] 
                                           HTTPRequestOperationWithRequest:request 
                                           success:^( AFHTTPRequestOperation *operation , id responseObject ){

                                             // Do something

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

                                             // Cancel all operations if you need to
                                             for (AFHTTPRequestOperation* operation in operations) {
                                               [operation cancel];
                                             }

                                           }];

  [operations addObject:operation];    
}

for (AFHTTPRequestOperation* operation in operations) {
  [[CustomHTTPClient sharedHTTPClient] enqueueHTTPRequestOperation:operation];
}

还有 enqueueBatchOfHTTPRequestOperations:progressBlock:completionBlock: 如果需要监控进度。

AFNetworking 项目: https ://github.com/AFNetworking/AFNetworking/

AFNetworking 文档: http ://afnetworking.org/Documentation/index.html

于 2012-07-21T18:28:26.853 回答