天天看点

解决WKWebview localstorage 存取信息不一致问题原因:解决方法代码如下

为了缩短开发周期。我们尝试使用 用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 存取信息不一致问题或者取不到的问题