How do I get a non-nil serverTrust value when creating a URLAuthenticationChallenge programmatically?

I realise that this is an older question but I ran into the same issue today while writing tests for my SSL pinning code. I solved it by subclassing URLProtectionSpace

private class TestURLProtectionSpace: URLProtectionSpace {
    var internalServerTrust: SecTrust?
    override var serverTrust: SecTrust? {
        return internalServerTrust
    }
}

let protectionSpace = TestURLProtectionSpace(
        host: "myhost.com",
        port: 443,
        protocol: "https",
        realm: nil,
        authenticationMethod: NSURLAuthenticationMethodServerTrust
)
protectionSpace.internalServerTrust = serverTrust

Tags:

Ios

Iphone

Swift