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

2018-08-31  本文已影响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"];

这行代码即可。

上一篇 下一篇

猜你喜欢

热点阅读