图片下载 - NSURLSession 收到身份验证挑战

Image download - NSURLSession received Authentication Challenge

我正在尝试从 url 下载简单图像 http://d1vqbpto5tbbz0.cloudfront.net/blog/wp-content/uploads/2014/08/25215844/ios-logo1.png

这很简单 url 通过浏览器访问,无需任何登录。

我试过这个代码:

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

为此,我正在接受身份验证质询。

这是什么原因?

我通过 Whosebug 找到了这些链接:

在所有链接中,都提到输入user:password。我可以输入什么用户名和密码?

您已实现 NSURLSessionDelegate 协议方法 didReceiveChallenge

每当发生身份验证挑战时,都会调用此方法。而且你必须提到它是一个受信任的服务器。

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

看起来问题很可能是由于该网站未使用 SSL/TSA。要处理挑战并加载图像,请遵循 NSURLSessionDelegate 委托并实施以下方法。

- (void)URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler;

编辑

另一种选择是在您的 plist 中指定任意加载以允许加载 HTTP 链接。不建议将其用于已发布的应用程序,但用于测试则更好。

将以下内容添加到您的 plist

<key>NSAppTransportSecurity</key>
<dict>
  <!--Include to allow all connections (DANGER)-->
  <key>NSAllowsArbitraryLoads</key>
      <true/>
</dict>