AFNetworking 3.0 下载 *.m4r 文件
Posted
技术标签:
【中文标题】AFNetworking 3.0 下载 *.m4r 文件【英文标题】:AFNetworking 3.0 download *.m4r file 【发布时间】:2016-12-06 09:01:40 【问题描述】:我有一个旧项目并尝试将其从 AFNetworking 2.* 更新到 AFNetworking 3.0。一切似乎都很好,除了下载 m4r 文件。旧代码使用了这样的东西:
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString]];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
AFHTTPRequestOperation* requestOperation = [[AFHTTPRequestOperation alloc] initWithRequest:request];
requestOperation.responseSerializer = [AFJSONResponseSerializer serializer];
requestOperation.outputStream = [NSOutputStream outputStreamToFileAtPath:outPath append:NO];
[requestOperation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation* operation, id responseObject)
//
failure:^(AFHTTPRequestOperation* operation, NSError* error)
//
];
[requestOperation setDownloadProgressBlock:downloadProgressBlock];
[requestOperation start];
我不确定,如何将带有输出流逻辑的逻辑移动到 AFNetwroking 3.0,所以现在我将其保留并重写了旧代码:
AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
manager.responseSerializer = [AFJSONResponseSerializer serializer];
[manager.responseSerializer setAcceptableContentTypes: [manager.responseSerializer.acceptableContentTypes setByAddingObjectsFromArray: @[@"video/mp4", @"audio/mpeg"]]];
manager.requestSerializer = [AFJSONRequestSerializer serializer];
[manager.requestSerializer setValue: @"gzip" forHTTPHeaderField: @"Accept-Encoding"];
[manager GET: URLString parameters: nil progress: downloadProgressBlock success: ^ (NSURLSessionTask* task, id responseObject)
//
failure: ^ (NSURLSessionTask* operation, NSError* error)
//
];
添加了设置可接受内容类型的行,因为没有它我收到描述错误:
“请求失败:不可接受的内容类型:video/mp4”
现在,在修复了这个错误之后,我得到了
"无法使用检测到的编码将数据转换为字符串。 数据可能已损坏。”
我做错了什么?
【问题讨论】:
【参考方案1】:我已经设法通过下载任务修复它。我的代码如下所示:
NSMutableURLRequest* request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:URLString]];
[request setValue:@"gzip" forHTTPHeaderField:@"Accept-Encoding"];
AFHTTPSessionManager* manager = [AFHTTPSessionManager manager];
NSURLSessionDownloadTask* downloadTask = [manager downloadTaskWithRequest: request progress: downloadProgressBlock destination: ^ NSURL*(NSURL* targetPath, NSURLResponse* response)
return [[NSURL alloc] initFileURLWithPath: outPath];
completionHandler: ^ (NSURLResponse* response, NSURL* filePath, NSError* error)
completion(error == nil, error);
];
[downloadTask resume];
【讨论】:
以上是关于AFNetworking 3.0 下载 *.m4r 文件的主要内容,如果未能解决你的问题,请参考以下文章
AFNetworking 3.0 setImageWithURLRequest 下载进度