WKWebView與JS交互,使用addScriptMessageHandler內存泄漏解決方案

??????? Xcode8發布以后,編譯器開始不支持IOS7,所以很多應用在適配IOS10之后都不在適配IOS7了,其中包括了很多大公司,網易新聞,滴滴出行等。

? ???? 支持到IOS8,第一個要改的自然是用WKWebView替換原來的UIWebView。

? ? ? WKWebview提供了API實現js交互 不需要借助JavaScriptCore或者webJavaScriptBridge。使用WKUserContentController實現js native交互。簡單的說就是先注冊約定好的方法,然后再調用。

代碼如下:


@interfaceViewController() <WKUIDelegate, WKNavigationDelegate, WKScriptMessageHandler>{? ?

? ? ? ? ? WKWebView * webView;?

? ? ? ? ? WKUserContentController* userContentController;

}

@end

@implementationViewController

#pragma mark - lifeCircle

- (void)viewDidLoad {?

? ? ? ? [superviewDidLoad];

? ? ? ? //配置環境WKWebViewConfiguration * configuration = [[WKWebViewConfiguration alloc]init];?

? ? ? userContentController =[[WKUserContentController alloc]init];? ? ? ? ? ? ? ? ? ? ? ? ? configuration.userContentController= userContentController;? ?

? ? ? webView = [[WKWebView alloc]initWithFrame:self.view.bounds? configuration:configuration];

? ? ? //注冊方法[userContentController addScriptMessageHandler:selfname:@"sayhello"];

? ? ? ? //注冊一個name為sayhello的js方法[self.viewaddSubview:webView];?

? ? ? ? webView.UIDelegate=self;?

? ? ? ? webView.navigationDelegate=self;?

? ? ? ? [webView loadRequest:[NSURLRequestrequestWithURL:?

? ? ? ? [NSURLURLWithString:@"http://www.test.com"]]];

}

- (void)dealloc{

//這里需要注意,前面增加過的方法一定要remove掉。

[userContentController removeScriptMessageHandlerForName:@"sayhello"];

}

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{

? ? ? ? NSLog(@"name:%@\\\\n body:%@\\\\n? ? ? ? ? frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);

}

@end


? ? ? ? 上面的OC代碼如果認證測試一下就會發現dealloc并不會執行,這樣肯定是不行的,會造成內存泄漏。原因是[userContentController addScriptMessageHandler:self? name:@"sayhello"];.如果大家在開發的時候沒有觀察dealloc的話就很容易忽略了這個問題了.這里WKUserContentController對象的addScriptMessageHandler方法的scriptMessageHandler參數傳入了將控制器本身(猜測addScriptMessageHandler將會對scriptMessageHandler參數傳入的對象做強引用,這點開發文檔沒有說明),而控制器又強引用了webView,然后webView又強引用了configuration,configuration又強引用了WKUserContentController對象,所以導致了引用循環,從而導致控制器不被釋放的問題.)因此還需要進一步改進。

? ? ? 只需要將[userContentController removeScriptMessageHandlerForName:@"sayhello"];這句話挪一下位置就可以了。我們可以在ViewController里加一個方法:

? -(void)popController {

? ? ? ? [userContentController removeScriptMessageHandlerForName:@"sayhello"];

??????? [self.navigationController popViewControllerAnimated:YES];

}

在控制器pop(或者dismiss)回去的時候remove就可以了。? ? ??

由于日常開發中用到webView的界面大部分都是二級以上的界面 ,所以在pop時remove是可行的。

今天就到這了,各位看官如果發現有什么不對的,請加qq:929949003,一起討論,謝謝!!

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容