Search code examples
iosobjective-cauthenticationnsurlsessionauthenticationchallenge

Image download - NSURLSession received Authentication Challenge


I'm trying to download simple image from url http://d1vqbpto5tbbz0.cloudfront.net/blog/wp-content/uploads/2014/08/25215844/ios-logo1.png

This is simple url access through browser without any login.

I have tried with this code:

NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
configuration.timeoutIntervalForRequest = timeout;
NSURLSession *urlSession = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
[[urlSession dataTaskWithURL:urlImage] resume];

For this only I am receiving authentication challenge.

What is the reason for it?

I have gone through stackoverflow and found these links:

In all links, there is mentioned to enter user:password. What user name and password, I can enter?


Solution

  • You have implement the NSURLSessionDelegate protocol method didReceiveChallenge.

    Whenever authentication challenge occurs this method will get calls. And you have to mention it is a trusted server.

    - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task
    didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge
     completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition
                                 disposition, NSURLCredential *credential))completionHandler
    {
        completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
    }