解决WKWebView加载的白屏问题
2017-07-18 本文已影响3347人
iOSser
解决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)
}