解决WKWebView加载的白屏问题

作者: iOSser | 来源:发表于2017-07-18 14:57 被阅读3347次

解决WKWebView加载的白屏问题

方法一:

objective - C 版

尝试在每次请求kWebview前清理缓存

/**
 清理缓存
 */
- (void)clearWbCache {
    [[NSURLCache sharedURLCache] removeAllCachedResponses];
    [[NSURLCache sharedURLCache] setDiskCapacity:0];
    [[NSURLCache sharedURLCache] setMemoryCapacity:0];
}

Swift 版

/// 清理缓存
    func clearCache() -> Void {
        URLCache.shared.removeAllCachedResponses();
        URLCache.shared.diskCapacity = 0;
        URLCache.shared.memoryCapacity = 0;
    }
方法二:

-- 服从代理协议并实现代理方法
objective - C 版本

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler {
     // 判断服务器采用的验证方法
    if (challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust) {
         // 如果没有错误的情况下 创建一个凭证,并使用证书
        if (challenge.previousFailureCount == 0) {
            NSURLCredential *credential = [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust];
            completionHandler(NSURLSessionAuthChallengeUseCredential, credential);
        }else {
        // 验证失败,取消本次验证
            completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);
        }
    }else {
        completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, nil);

    }
}


Swfit 版本

func webView(webView: WKWebView, didReceiveAuthenticationChallenge challenge: NSURLAuthenticationChallenge, completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Void) {
        // 判断服务器采用的验证方法
    if challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust {
        if challenge.previousFailureCount == 0 {
            // 如果没有错误的情况下 创建一个凭证,并使用证书
            let credential = NSURLCredential(forTrust: challenge.protectionSpace.serverTrust!)
            completionHandler(.UseCredential, credential)
        } else {
            // 验证失败,取消本次验证
            completionHandler(.CancelAuthenticationChallenge, nil)
        }
    } else {
        completionHandler(.CancelAuthenticationChallenge, nil)
    }

相关文章

网友评论

  • 3245062a573d:大神我按照你这个做了,白屏问题还是没有解决,求指教
  • 青空逸隐:[self.webView loadRequest:[NSURLRequest requestWithURL:<#(nonnull NSURL *)#> cachePolicy:<#(NSURLRequestCachePolicy)#> timeoutInterval:<#(NSTimeInterval)#>]]
  • Tatinic:WKWebView 根本就不走 NSURL 相关的方法。
    你确定方法一不是用来搞笑的吗?
    iOSser:@Tatinic 那你觉得WKWebView的缓存在哪里
    Tatinic:@iOSser 是呀是呀,WKWebView 不会走 app 的 NSURLSession 进行网络请求。也不会去到 app 的 NSURLCache 查询缓存的内容,也不会走 NSURLProtocol 相关的方法……
    iOSser:@Tatinic 你好感谢您的评论,方法一是要自己去调用清理缓存的!
  • Sam129:请问出现这个问题的原因是什么?
    3245062a573d:大神我按照你这个做了,白屏问题还是没有解决,求指教
    iOSser:原因1:网络比较慢, 没加在出来白屏!
    原因2:这个WKWebView好像有个bug, 可以在小于iOS8.2的时候选择UIWebVIew 或则你只是使用UIWebView

本文标题:解决WKWebView加载的白屏问题

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