Apollo iOS 团队的 Ellen Shapiro 非常友好地为我指明了正确的方向。这就是我最终得到的结果:
public struct PromiscuousApolloClientFactory {
/// Creates an `ApolloClient` instance that is configured to work with certificates that the
/// OS would otherwise deem invalid, like those that are self-signed.
/// - Parameter endpointURL: The URL of the GraphQL endpoint.
/// - Returns: The configured `ApolloClient` instance.
public static func make( with endpointURL: URL ) -> ApolloClient {
let store = ApolloStore( cache: InMemoryNormalizedCache() )
let sessionConfig = URLSessionConfiguration.default
let client = PromiscuousURLSessionClient( sessionConfiguration: sessionConfig )
let provider = LegacyInterceptorProvider( client: client, store: store )
let transport = RequestChainNetworkTransport( interceptorProvider: provider, endpointURL: endpointURL )
return ApolloClient( networkTransport: transport, store: store )
}
}
private class PromiscuousURLSessionClient: URLSessionClient {
override func urlSession( _ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping ( URLSession.AuthChallengeDisposition, URLCredential? ) -> Void ) {
let protectionSpace = challenge.protectionSpace
guard protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust,
let serverTrust = protectionSpace.serverTrust else {
completionHandler( .performDefaultHandling, nil )
return
}
let credential = URLCredential( trust: serverTrust )
completionHandler( .useCredential, credential )
}
}
注意 BENE:这通常是一种不好的做法,因为它会短路安全保护措施,这些保护措施是为了您自己的利益。如果您有使用操作系统可以验证的证书的路径,请改为这样做。:)