关于下载资源,您可以使用 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