この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;
}