為了縮短開發周期。我們嘗試使用 用webview 加載html頁面的方式,實作安卓、iOS開發的同步進行。
UIWebview 存在記憶體洩露問題,iOS8以後,蘋果推出了新架構Webkit,提供了替換UIWebView的元件WKWebView。
WKWebView 在記憶體占用上優化的很多。但是在實踐中發現bug:localstorage資訊不一緻。
A頁面和B頁面都存在 一個WKWebView。 在B頁面使用localstorage儲存資訊。 回到A頁面取不到最新的資料。
原因:
wkwebviewconfiguration 中有個屬性 processPool,描述是:The process pool from which to obtain the view’s Web Content process.
解決方法
将WKWebViewConfiguration中的processPool 設定成一個 也就是可以使用單利的形式進行建立使這個資源池達到共享
代碼如下
@interface ZTWkProcessPool : WKProcessPool
+ (instancetype)singleWkProcessPool;
@end
@implementation ZTWkProcessPool
+ (instancetype)singleWkProcessPool{
static ZTWkProcessPool *staticInstance;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
staticInstance = [[self alloc] init];
});
return staticInstance;
}
@end
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.processPool = [ZTWkProcessPool singleWkProcessPool];
pWebView = [[tztWKWebView alloc] initWithFrame:self.bounds configuration:config];
這樣就解決了WKWebview localstorage 存取資訊不一緻問題或者取不到的問題