WKWebView加载https网页时显示白屏的解决办法

19-01-15 00:14 字数 1389 阅读 11160

今天在使用WKWebView加载十七度时发现view一片空白,毫无疑问加载失败了。

#import <WebKit/WebKit.h>

- (void)viewDidLoad
{
    [super viewDidLoad];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://www.shiqidu.com"]];
    [webView loadRequest:request];
    [self.view addSubview:webView];
}

很简单的代码但是网页死活就是加载不出来,百度之后发现很多人遇见了这种问题,后来发现是网站的证书有问题,不合法,所以导致加载失败,在设置navigationDelegate后,实现下面的代理方法可以看到报错信息。

webView.navigationDelegate = self;
// ...
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error
{
    NSLog(@"加载失败%@", error.userInfo);
}

报错信息如下

加载失败{
    NSErrorClientCertificateStateKey = 0;
    NSErrorFailingURLKey = "https://www.shiqidu.com/";
    NSErrorFailingURLStringKey = "https://www.shiqidu.com/";
    NSErrorPeerCertificateChainKey =     (
        "<cert(0x7fd562e070a0) s: shiqidu.com i: Avast trusted CA>"
    );
    NSLocalizedDescription = "The certificate for this server is invalid. You might be connecting to a server that is pretending to be \U201cwww.shiqidu.com\U201d which could put your confidential information at risk.";
    NSLocalizedRecoverySuggestion = "Would you like to connect to the server anyway?";
    NSURLErrorFailingURLPeerTrustErrorKey = "<SecTrustRef: 0x600002d2c990>";
    NSUnderlyingError = "Error Domain=kCFErrorDomainCFNetwork Code=-1202 \"(null)\" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, _kCFNetworkCFStreamSSLErrorOriginalValue=-9807, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9807}";
    "_NSURLErrorFailingURLSessionTaskErrorKey" = "LocalDataTask <9AD035CF-0A85-40B3-9E37-1D3FF739D9

从报错信息大概可以看出是因为ssl证书不合法导致加载失败,如果想要正常加载网页,需要做如下的处理。

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *_Nullable))completionHandler
{
    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
        if (challenge.previousFailureCount == 0) {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        } else {
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
    }
}

实现didReceiveAuthenticationChallenge:这个方法后,重新run一次,发现网页终于正常加载了。

0人点赞>
关注 收藏 改进 举报
0 条评论
排序方式 时间 投票
快来抢占一楼吧
请登录后发表评论
站长 @ 十七度
文章
384
粉丝
23
喜欢
195
收藏
31
排名 : 1
访问 : 144.97万
私信