我最近更新了AFNetworking 2.0。该文档称它与iOS6.0 +兼容。当我尝试实现下载方法(图像和视频)时,我正在构建iOS 6.0应用程序。示例使用
AFURLSessionManager *manager = [[AFURLSessionManager alloc] initWithSessionConfiguration:configuration];
然而,我得到了一个"使用未声明的标识符' AFURLSessionManager'"错误。我发现AFURLSessionManager使用的是只能从iOS7获得的类。我只是想知道,我可以使用AFNetworking在iOS6下载谁?
另外,有没有看到下载进度?
谢谢
答案 0 :(得分:4)
您可以使用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;
}
答案 1 :(得分:2)
正如您所说AFURLSessionManager
仅在iOS 7中可用(由NSURLSession
支持),因此您应该使用AFNetworking 2.0中基于NSURLConnection
的类(AFHTTPRequestOperationManager
, AFHTTPRequestOperation
等。)
答案 2 :(得分:2)
试试这个......
AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
manager.responseSerializer = [AFHTTPResponseSerializer serializer];
AFHTTPRequestOperation *operation = [manager GET:urlString
parameters:nil
success:^(AFHTTPRequestOperation *operation, NSData *responseData)
{
[responseData writeToURL:someLocalURL atomically:YES];
}
failure:^(AFHTTPRequestOperation *operation, NSError *error)
{
NSLog(@"Downloading error: %@", error);
}];
[operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead)
{
float downloadPercentage = (float)totalBytesRead/(float)(totalBytesExpectedToRead);
[someProgressView setProgress:downloadPercentage animated:YES];
}];