Search code examples
iosoauth-2.0afnetworkingafnetworking-2

Download a file with AFHTTPSessionManager and with authentication


I'm working on an iOS app using OAuth2 authentication.

I'm authenticated, I have no problem requesting my API, but I'm facing a problem when trying to download some files from protected URLS.

I'm using downloadTaskWithRequest from AFURLSessionManager (AFNetworking). It returns always an error 401 (not authorized) as if I was not logged in.

I can access this URL with no problem if I use the GET method, but I would like to use downloadTaskWithRequest because it permits me to have a progress indicator.

Here's my code (which isn't working):

NSURLSessionDownloadTask *downloadTask = [apiC downloadTaskWithRequest:request progress:nil destination:^NSURL *(NSURL *targetPath, NSURLResponse *response) {
     NSURL *dstPath = [NSURL fileURLWithPath:dstFilePath];
    return dstPath;

} completionHandler:^(NSURLResponse *response, NSURL *filePath, NSError *error) {

    // HERE I HAVE A 401
}];

Here's my code that does work:

[[OEOApiClient sharedClient] GET:url parameters:nil success:^(NSURLSessionDataTask *task, id responseObject) {
    // SUCCEDD !!
} failure:^(NSURLSessionDataTask *task, NSError *error) {
}];

Does downloadTaskWithRequest not support authentication? Am I doing something wrong?


Solution

  • OK, I was creating my request the wrong way :

    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
    

    this was the good way :

    NSURLRequest *request = [mySessionManager.requestSerializer requestWithMethod:@"GET" URLString:url parameters:nil error:&serializationError];