关于ios:AFNetworking 3.0下载*.m4r文件

AFNetworking 3.0 download *.m4r file

我有一个旧项目并尝试将其从 AFNetworking 2.* 更新到 AFNetworking 3.0。一切似乎都很好,除了下载 m4r 文件。旧代码使用了这样的东西:

1
2
3
4
5
6
7
8
9
10
11
12
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,所以现在我将其保留并重写旧代码:

1
2
3
4
5
6
7
8
9
10
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) {
        //
}];

添加了设置可接受内容类型的行,因为没有它我收到描述错误:

“Request failed: unacceptable content-type: video/mp4”

现在,在修复了这个错误之后,我得到了

“Unable to convert data to a string using the detected encoding. The
data may be corrupt.”

我做错了什么?


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

1
2
3
4
5
6
7
8
9
10
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];


原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/268710.html

(0)
上一篇 2022年6月20日
下一篇 2022年6月20日

相关推荐

发表回复

登录后才能评论