1.内存泄漏
现象:WKWebView所在的ViewController不执行dealloc
原因:下面的代码引起
WKWebViewConfiguration * wkconfiguration = [[WKWebViewConfiguration alloc]init];
// userContentController 强引用了 self (控制器)
[wkconfiguration.userContentController addScriptMessageHandler:self name:@"JsBridge"];
如果没有执行对应的removeScriptMessageHandlerForName,就会造成内存泄漏。
解决办法:
方法1.新建一个类
WeakScriptMessageDelegate.h
#import <Foundation/Foundation.h>
#import <WebKit/WebKit.h>
@interface WeakScriptMessageDelegate : NSObject<WKScriptMessageHandler>
@property (nonatomic,weak)id<WKScriptMessageHandler> scriptDelegate;
- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate;
@end
WeakScriptMessageDelegate.m
#import "WeakScriptMessageDelegate.h"
@implementation WeakScriptMessageDelegate
- (instancetype)initWithDelegate:(id<WKScriptMessageHandler>)scriptDelegate{
self = [super init];
if (self) {
_scriptDelegate = scriptDelegate;
}
return self;
}
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
[self.scriptDelegate userContentController:userContentController didReceiveScriptMessage:message];
}
@end
然后对应改成:
WKWebViewConfiguration * wkconfiguration = [[WKWebViewConfiguration alloc]init];
[wkconfiguration.userContentController addScriptMessageHandler:[[WeakScriptMessageDelegate alloc] initWithDelegate:self] name:@"JsBridge"];
方法2:(不建议用这个)
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"JsBridge"];
}
//因为移除后跟js的交互就失效了,viewWillDisappear并不代表dealloc了
2.页面空白
现象: 有时候返回到上一个页面发现页面变空白了,或者从后台切会到前台后发现页面空白了
原因:我猜测是内存扛不住了
解决办法:(9.0及以后)
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
//reload你的URL
}
//注意这个是wkwebview.navigationDelegate的协议