美文网首页
iOS WKWebView信任Https请求(自签名证书)

iOS WKWebView信任Https请求(自签名证书)

作者: 权宜平和 | 来源:发表于2018-08-31 16:39 被阅读666次

步骤如下:
一、新建一个NSURLRequest的类别
二、在这个类别中新增两个类方法,如下:

+ (BOOL)allowsAnyHTTPSCertificateForHost:(NSString *)host {
    return YES;
}

+ (void)setAllowsAnyHTTPSCertificate:(BOOL)allow forHost:(NSString *)host {
    
}

注:这两个方法是系统的私有方法

三、实现WKWebView的代理方法(- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler),实现代码如下:

#pragma mark - wkwebview信任https接口
- (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);
    }
}

四、在加载webView的URL之前调用

[NSURLRequest setAllowsAnyHTTPSCertificate:YES forHost:@"https"];

这行代码即可。

相关文章

网友评论

      本文标题:iOS WKWebView信任Https请求(自签名证书)

      本文链接:https://www.haomeiwen.com/subject/gqfewftx.html