0

I am trying to query an endpoint that includes HTTPS and Self Signed Certificate. How would I implement the code below to include a certificate using Combine in 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()
    }
}

For example without using Combine I normally do the following:

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)
        }
    }
}
New Dev
  • 48,427
  • 12
  • 87
  • 129
CableGuy
  • 47
  • 1
  • 6

1 Answers1

1

You can't do this with URLSession.shared, because the session's delegate has to accept the self-signed certificate.

Your question shows that you already know how to use a delegate for this. So change getJSON to accept an appropriately-delegated session as an argument:

    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()
    }
rob mayoff
  • 375,296
  • 67
  • 796
  • 848