Search code examples
iosafnetworking-2afnetworking-3

AFNetworking 3.0 download *.m4r file


I have an old project and try to update it from AFNetworking 2.* to AFNetworking 3.0. Everything seems to work fine, except downloading m4r files. Old code used something like this:

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

I'm not sure, how to move logic with output stream logic to AFNetwroking 3.0, so for now I left it and rewrote old code with:

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) {
        //
}];

The line with setting acceptableContentTypes is added, because without it I was receiving an error with description:

"Request failed: unacceptable content-type: video/mp4"

Now, after fixing this error, I'm getting

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

What am I doing wrong?


Solution

  • I've managed to fix it with download task. My code looks like this:

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