我正在尝试查询包含 HTTPS 和自签名证书的端点。我将如何实现下面的代码以包含在 Swift 中使用组合的证书。
struct API {
func getJSON() -> AnyPublisher<ResultList, Error> {
let url = URL(string:urlString)!
return URLSession.shared.dataTaskPublisher(for: url)
.map({$0.data})
.decode(type: ResultList.self, decoder: JSONDecoder())
.receive(on: RunLoop.main)
.eraseToAnyPublisher()
}
}
例如,不使用 Combine 我通常会执行以下操作:
class SessionDelegate: NSObject, URLSessionDelegate {
public func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
if challenge.protectionSpace.host == myCert {
completion(.useCredential, URLCredential(trust: challenge.protectionSpace.serverTrust!))
} else {
completion(.performDefaultHandling, nil)
}
}
}