背景
項目中使用了wkwebview替換了之前的uiwebview,牽扯到hybird開發,我們需要和h5交互,所以用到了wkwebviewconfiguration 中的 wkusercontentcontroller
所以初始化代碼如下
1
2
3
4
5
6
7
8
9
10
11
|
wkusercontentcontroller *usercontentcontroller = [[wkusercontentcontroller alloc] init]; [usercontentcontroller addscriptmessagehandler:self name:getkeyiosandroid_action]; [usercontentcontroller addscriptmessagehandler:self name:upload_action]; // wkwebview的配置 wkwebviewconfiguration *configuration = [[wkwebviewconfiguration alloc] init]; configuration.usercontentcontroller = usercontentcontroller; _webview = [[wkwebview alloc] initwithframe:cgrectzero configuration:configuration]; _webview.navigationdelegate = self; _webview.uidelegate = self; |
getkeyiosandroid_action upload_action 分別是h5通過message handler的方式來調用oc的兩個方法。
這時,就已經發生了隱患,因為
[usercontentcontroller addscriptmessagehandler:self name:getkeyiosandroid_action];
這里usercontentcontroller持有了self ,然后 usercontentcontroller 又被configuration持有,最終唄webview持有,然后webview是self的一個私有變量,所以self也持有self,所以,這個時候有循環引用的問題存在,導致界面被pop或者dismiss之后依然會存在內存中。不會被釋放
當然如果你只是靜態界面,或者與h5的交互的內容僅限于本頁面內的內容,其實只是單純的內存泄漏,但是,如果此時和h5的交互方法中牽扯到全局變量,或者全局的一些內容,那么就不可控制了。
我發現這個問題是因為我們web頁面會監聽token過期的和登錄狀態改變的通知,然后會刷新界面,并且重新發送請求,這一系列動作中會和用戶的全局信息進行交互,所以在訪問一個web頁面后,切換賬號登錄時會發現有之前訪問過的web頁面請求發出,并且因為token不同報了token過期的錯誤,所以導致登錄后誤操作為token過期,緊接著被踢到登錄界面。
通過charles抓包發現,這些web頁面都是在切換登錄賬號欠訪問的所有界面,所以,鎖定問題時web頁面依舊存在,在切換登錄后收到了登錄狀態改變的通知,重新刷新了界面導致請求發出并返回報錯,進而出現登錄后被踢出的bug。
解決方案:
既然是循環引用,那么必須破除一邊的強引用,改為弱引用,或者直接去除引用。思路明朗了。。
嘗試1:
1
2
3
|
id __weak weakself = self; wkusercontentcontroller *usercontentcontroller = [[wkusercontentcontroller alloc] init]; [usercontentcontroller addscriptmessagehandler:weakself name:getkeyiosandroid_action]; |
思路效仿block , 結果失敗
嘗試2:
在viewwilldisappear / viewdiddisappear 生命周期方法中調用
1
|
[_webview.configuration.usercontentcontroller removealluserscripts]; |
這算一個腦抽的嘗試,看文檔說明就懂了。自行略過
嘗試3:
不在初始化時添加scriptmessagehandler, 而是和notificenter/kvc一個思路
1
2
3
4
5
6
7
8
9
10
11
12
13
|
- ( void )viewwillappear:( bool )animated { [super viewwillappear:animated]; [_webview.configuration.usercontentcontroller addscriptmessagehandler:self name:getkeyiosandroid_action]; [_webview.configuration.usercontentcontroller addscriptmessagehandler:self name:upload_action]; } - ( void )viewwilldisappear:( bool )animated { [super viewwilldisappear:animated]; [_webview.configuration.usercontentcontroller removescriptmessagehandlerforname:getkeyiosandroid_action]; [_webview.configuration.usercontentcontroller removescriptmessagehandlerforname:upload_action]; } |
結果成功
小結:
之前在使用wkwebview的時候很多blog的內容都只是說了怎么添加message handler 但是并沒有高速大家有這個內存泄漏的風險,如果你只是頁面內的數據調用你壓根都不會發現這個問題。
此坑已填!
總結
以上就是這篇文章的全部內容了,希望本文的內容對大家的學習或者工作具有一定的參考學習價值,如果有疑問大家可以留言交流,謝謝大家對服務器之家的支持。
原文鏈接:https://blog.csdn.net/wxs0124/article/details/78402596