AFNetworking 3.0下载* .m4r文件

时间:2016-12-06 09:01:40

标签: ios afnetworking-2 afnetworking-3

我有一个旧项目,并尝试将其从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) {
        //
}];

添加了设置acceptableContentTypes的行,因为没有它我收到了描述错误:

  

“请求失败:不可接受的内容类型:video / mp4”

现在,在修复此错误后,我正在

  

“无法使用检测到的编码将数据转换为字符串   数据可能已损坏。“

我做错了什么?

1 个答案:

答案 0 :(得分:0)

我已设法通过下载任务修复它。我的代码如下所示:

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];