Accept self signed certificate in WKWebView

I am trying to load local resources in a WKWebView using HTTPS and a local web server. I've used Telegraph to implement the local web server. The local web server is using a self signed certificate. I understand that the implementation below of this WKNavigationDelegate method is necessary to accept a web server's self signed certificate. I've managed to get the WKWebView to load local resources on iOS 11 and above, but the method below is not called for the localhost on iOS 10 and I have seen this error in the Safari Web Inspector:

Failed to load resource: The certificate for this server is invalid. You might be connecting to a server that is pretending to be “localhost” which could put your confidential information at risk.


- (void)webViewDidReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *_Nullable))completionHandler

{

    NSString *authenticationMethod = challenge.protectionSpace.authenticationMethod;

    if ([authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust])

    {

        NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];

        completionHandler(NSURLSessionAuthChallengeUseCredential, credential);

        return;

    }


    completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}


Is there a way to fix the error above and accept self signed certificates on iOS 10?

Replies

You don't need to use https on localhost. For older OS versions, you may need to specify arbitrary loads. But newer versions allow NSAllowsLocalNetworking = true for NSAppTransportSecurity

Thanks for your reply. That's a good suggestion. However, it's not a viable solution in this case, because the resources located in the local host need to be loaded using a secure connection. These resources are retrieved from a host page that needs to be served through HTTPS and WebKit doesn't seem to allow them to be loaded over an insecure connection.