我首先使用AFHTTPClient下载单个索引文档,并使用CoreData记录每个记录.然后我需要启动一个单独的进程来下载每个单独的记录.最好的方法是什么?
为每个资源提出请求并让它们完成是否合理?可能有一百左右.
或者,我可以加载第一个,提交请求,然后加载成功并提交后续请求.
我正在使用CoreData更新数据库,我认为这意味着我需要为每个请求分别拥有一个NSManagedObjectContent?
我也很想知道,AFHTTPClient是在主线程上执行回调,还是在发起请求的线程上执行回调?我宁愿没有阻止主线程执行CoreData I / O.
最佳答案 关于下载资源,您可以使用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