WKWebView加载网页
当WKWebView与js交互时,会发生内存泄漏,造成webview无法释放。这可能造成进行js交互时响应异常
创建js交互的webview
//懒加载创建视图,并增加js监听
- (WKWebView *)webView {
if (!_webView) {
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = [WKUserContentController new];
[configuration.userContentController addScriptMessageHandler:self name:@"goBack"];
[configuration.userContentController addScriptMessageHandler:self name:@"getTokenInfo"];
// [configuration.userContentController addScriptMessageHandler:self name:@"toPayWechat"];
// [configuration.userContentController addScriptMessageHandler:self name:@"toPayAlipay"];
[configuration.userContentController addScriptMessageHandler:self name:@"toPayApple"];
[configuration.userContentController addScriptMessageHandler:self name:@"openUserAgreement"];
[configuration.preferences setValue:@YES forKey:@"allowFileAccessFromFileURLs"];
if (@available(iOS 10.0, *)) {
[configuration setValue:@YES forKey:@"allowUniversalAccessFromFileURLs"];
}
WKPreferences *preferences = [WKPreferences new];
preferences.javaScriptCanOpenWindowsAutomatically = YES;
preferences.minimumFontSize = 10;
configuration.preferences = preferences;
_webView = [[WKWebView alloc] initWithFrame:CGRectZero configuration:configuration];
_webView.navigationDelegate = self;
_webView.UIDelegate = self;
_webView.scrollView.backgroundColor = [UIColor whiteColor];
// _webView.allowsBackForwardNavigationGestures = YES;
// 垂直滚动
//[_webView.scrollView setShowsVerticalScrollIndicator:NO];
_webView.scrollView.bounces = NO;
if (@available(iOS 11.0, *)) {
_webView.scrollView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
}
}
return _webView;
}
解决泄漏
remove需要一一对应,dealloc中增加方法即可
//生命周期退出前,手动删除js交互,否则内存泄漏
- (void)removeJs{
[_webView.configuration.userContentController removeScriptMessageHandlerForName:@"goBack"];
[_webView.configuration.userContentController removeScriptMessageHandlerForName:@"getTokenInfo"];
[_webView.configuration.userContentController removeScriptMessageHandlerForName:@"toPayApple"];
[_webView.configuration.userContentController removeScriptMessageHandlerForName:@"openUserAgreement"];
}
网友评论