1.內(nèi)存泄漏
現(xiàn)象:WKWebView所在的ViewController不執(zhí)行dealloc
原因:下面的代碼引起
WKWebViewConfiguration * wkconfiguration = [[WKWebViewConfiguration alloc]init];
// userContentController 強引用了 self (控制器)
[wkconfiguration.userContentController addScriptMessageHandler:self name:@"JsBridge"];
如果沒有執(zhí)行對應(yīng)的removeScriptMessageHandlerForName,就會造成內(nèi)存泄漏。
解決辦法:
方法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
然后對應(yīng)改成:
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.頁面空白
現(xiàn)象: 有時候返回到上一個頁面發(fā)現(xiàn)頁面變空白了,或者從后臺切會到前臺后發(fā)現(xiàn)頁面空白了
原因:我猜測是內(nèi)存扛不住了
解決辦法:(9.0及以后)
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
//reload你的URL
}
//注意這個是wkwebview.navigationDelegate的協(xié)議