我有一个名为的自定义委托类CertificatePinningDelegate,它符合URLSessionDelegate. 我正在使用委托方法
urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void)
Run Code Online (Sandbox Code Playgroud)
与服务器进行身份验证。现在我想为此编写一个单元测试。
我一直在尝试手动调用委托方法来传递自定义URLAuthenticationChallenge对象,这似乎是不可能的。有谁知道有什么替代/更好的选择吗?
xcode unit-testing swift urlsession urlauthenticationchallenges
我正在尝试从 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()
}
Run Code Online (Sandbox Code Playgroud)
这调用了它的委托方法
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))")
}
}
Run Code Online (Sandbox Code Playgroud)
URLAuthenticationChallenges 保护空间始终是 serverTrust。当尝试访问 PDF …