iOS WKWebView 加载过程中出现白屏的解决方案
程序员文章站
2022-05-28 21:50:14
...
在放置webView的ViewController里添加以下代码
#pragma mark -- 解决首次加载白屏的问题 -- - (void)viewWillAppear:(BOOL)animated { [super viewWillAppear:animated]; if (self.webView.title == nil) { [self.webView reload]; } }
遵守WKNavigationDelegate 协议 实现代理 #pragma mark - WKNavigationDelegate - (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView NS_AVAILABLE(10_11, 9_0){ [webView reload]; }
// 监听事件处理 - (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context{ if(object == self.webView && [keyPath isEqualToString:@"URL"]) { NSURL *newUrl = [change objectForKey:NSKeyValueChangeNewKey]; NSURL *oldUrl = [change objectForKey:NSKeyValueChangeOldKey]; if (objectIsNull(newUrl) && !objectIsNull(oldUrl)) { [self.webView reload]; }; } } staticinlineBOOLobjectIsNull(id obj) { if (obj == nil) { return YES; } if ([obj isKindOfClass:[NSString class]]) { return ((NSString *)obj).length == 0; } if ([obj isKindOfClass:[NSArray class]]) { NSArray *arr = (NSArray *)obj; return arr.count == 0; } if ([obj isKindOfClass:[NSDictionary class]]) { NSDictionary *dic = (NSDictionary *)obj; return dic.count == 0; } if ([obj isKindOfClass:[NSNull class]]) { return YES; } returnNO; }
以上代码说是可以解决%90的WKWebView加载白屏,我加上之后暂时还没出现白屏