WKWebView and self signed certificate

There is some history for this question on archived forums https://devforums.apple.com/message/1064578#1064578

but unfortunately it's left without real solution.


So, is there any way to open URL from dev server with self signed certificate in WKWebView?


At first I thought that something like this can help:

    func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
        decisionHandler(WKNavigationActionPolicy.Allow)
    }

but I was wrong.


Also,

func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void)

still doesn't get called at all.


Are there some workarounds that you know about?

Replies

I used the WKNavigationDelegate and implemented this to make it work:


- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential *credential))completionHandler {

NSLog(@"Allow all");

SecTrustRef serverTrust = challenge.protectionSpace.serverTrust;

CFDataRef exceptions = SecTrustCopyExceptions (serverTrust);

SecTrustSetExceptions (serverTrust, exceptions);

CFRelease (exceptions);

completionHandler (NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:serverTrust]);

}

Hi MrJones,


Dyou have a swift counterpart for this code? Newbie here.


Thanks

I just came across this. Here's the delegate method implemented in Swift 3.1:


func webView(_ webView: WKWebView, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
        guard let serverTrust = challenge.protectionSpace.serverTrust else { return completionHandler(.useCredential, nil) }
        let exceptions = SecTrustCopyExceptions(serverTrust)
        SecTrustSetExceptions(serverTrust, exceptions)
        completionHandler(.useCredential, URLCredential(trust: serverTrust))
    }