我正在尝试从 URL 下载 PDF。
private func downloadSessionWithFileURL(_ url: URL){
var request = URLRequest(url: url)
request.addValue("gzip, deflate", forHTTPHeaderField: "Accept-Encoding")
let sessionConfig = URLSessionConfiguration.default
let session = URLSession(configuration: sessionConfig, delegate: self, delegateQueue: nil)
session.downloadTask(with: request).resume()
}
这调用了它的委托方法
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.previousFailureCount > 0 {
completionHandler(Foundation.URLSession.AuthChallengeDisposition.cancelAuthenticationChallenge, nil)
}
if let serverTrust = challenge.protectionSpace.serverTrust {
completionHandler(Foundation.URLSession.AuthChallengeDisposition.useCredential, URLCredential(trust: serverTrust))
} else {
print("unknown state. error: \(String(describing: challenge.error))")
}
}
URLAuthenticationChallenges protectionSpace 始终是 serverTrust。当试图访问 PDF 的 URL 时,它会将用户重定向到登录屏幕。我原以为会有另一个电话
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
要求用户输入他们的凭据,但没有。因此下载任务尝试下载重定向 URL 的内容,这是一个登录屏幕。
我的问题是。
1.什么触发了用户名和密码的 URLAuthenticationChallenge。它是 HTML 中的特定标头值吗?
- 对于来自服务器的用户名密码请求,我应该期待哪个 URLAuthenticationChallenge protectionSpace。