强制打开https证书无效的网址

有时候一些特定的网页是使用HTTPS的,但是有可能HTTPS证书过期失效,这时候如果直接使用web打开,就会报错。

Error Domain=NSURLErrorDomain Code=-1202 “The certificate for this server is invalid.

可以在web的代理方法中执行下面的方法,强制信任无效的HTTPS证书

代码示例是WKWebView

1
2
3
4
5
6
7
8
9
10
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{

if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {

NSURLCredential *card = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];

completionHandler(NSURLSessionAuthChallengeUseCredential,card);

}
}