0

我正在尝试查询包含 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)
        }
    }
}
4

1 回答 1

0

您不能使用 执行此操作URLSession.shared,因为会话的委托人必须接受自签名证书。

您的问题表明您已经知道如何为此使用委托。因此,更改getJSON为接受适当委派的会话作为参数:

    func getJSON(with session: URLSession) -> AnyPublisher<ResultList, Error> {
        let url = URL(string:urlString)!
        return session.dataTaskPublisher(for: url)
            .map({$0.data})
            .decode(type: ResultList.self, decoder: JSONDecoder())
            .receive(on: RunLoop.main)
            .eraseToAnyPublisher()
    }
于 2021-03-23T18:31:38.820 回答