您可以使用AFHTTPRequestOperation
该类在 iOS 6 上执行文件下载。您基本上只需要设置操作的outputStream
属性来存储文件和downloadProgressBlock
属性来监视进度。
下面的基本方法是在一个类中声明的,该类是AFHTTPRequestOperationManager
. 当我初始化这个类的一个实例时,我设置了baseURL
属性。
- (AFHTTPRequestOperation *)downloadFileWithContentId:(NSString *)contentId destination:(NSString*)destinationPath {
NSString *relativeURLString = [NSString stringWithFormat:@"api/library/zipped/%@.zip", contentId];
NSString *absoluteURLString = [[NSURL URLWithString:relativeURLString relativeToURL:self.baseURL] absoluteString];
NSMutableURLRequest *request = [self.requestSerializer requestWithMethod:@"GET" URLString:absoluteURLString parameters:nil];
void (^successBlock)(AFHTTPRequestOperation *operation, id responseObject) = ^void(AFHTTPRequestOperation *operation, id responseObject) {
};
void (^failureBlock)(AFHTTPRequestOperation *operation, NSError *error) = ^void(AFHTTPRequestOperation *operation, NSError *error) {
};
AFHTTPRequestOperation *operation = [self HTTPRequestOperationWithRequest:request success:successBlock failure:failureBlock];
NSOutputStream *outputStream = [NSOutputStream outputStreamToFileAtPath:destinationPath append:NO];
operation.outputStream = outputStream;
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) {
}];
[self.operationQueue addOperation:operation];
return operation;
}