iOS中WKWebView,存在首次加載h5頁面,h5頁面中的js就拿不到localstorage了。
WKWebView localStorage 緩存很嚴重
HTML5在客戶端存儲數(shù)據(jù)的方式:cookie , localStorage, sessionStorage
cookie:只能存儲少量的數(shù)據(jù), 常用來存儲賬號密碼等
localStorage : 沒有時間限制的數(shù)據(jù)存儲
sessionStorage : 針對一個 session 的數(shù)據(jù)存儲, 當網(wǎng)頁關閉時,數(shù)據(jù)也會被刪除。
1.WKWebView設置localStorage
NSString * userContent = [NSString stringWithFormat:@"{"token": "%@", "userId": %@}", @"a1cd4a59-974f-44ab-b264-46400f26c849", @"89"];
// 設置localStorage
NSString *jsString = [NSString stringWithFormat:@"localStorage.setItem('userContent', '%@')", userContent];
// 移除localStorage
// NSString *jsString = @"localStorage.removeItem('userContent')";
// 獲取localStorage
// NSString *jsString = @"localStorage.getItem('userContent')";
[self.webView evaluateJavaScript:jsString completionHandler:nil];
NSString * userContent = @"{"name": "Tom", "age": 10}"];
// 設置localStorage
NSString *jsString = [NSString stringWithFormat:@"localStorage.setItem('userContent', '%@')", userContent];
// 移除localStorage
// NSString *jsString = @"localStorage.removeItem('userContent')";
// 獲取localStorage
// NSString *jsString = @"localStorage.getItem('userContent')";
[self.webView stringByEvaluatingJavaScriptFromString:jsString];
//清理掉所有的localStorage數(shù)據(jù)
//NSString *clearString = @"localStorage.clear()";
iOS wkwebview localstorage數(shù)據(jù)處理
WKWebView 在內存占用上優(yōu)化的很多。但是在實踐中發(fā)現(xiàn)bug:localstorage信息不一致。
A頁面和B頁面都存在 一個WKWebView。 在B頁面使用localstorage保存信息。 回到A頁面取不到最新的數(shù)據(jù)。
原因:
https://developer.apple.com/reference/webkit/wkwebviewconfiguration 中有個屬性 processPool,描述是:The process pool from which to obtain the view’s Web Content process.
解決方法:
把config中的processPool變?yōu)閱卫蚕?/p>
-
(WKProcessPool*)singleWkProcessPool{
staticWKProcessPool*sharedPool;
staticdispatch_once_tonceToken;
dispatch_once(&onceToken, ^{
sharedPool = [[WKProcessPoolalloc]init];});
returnsharedPool;
}
設置webview的配置 config.processPool = [NYWKWebView singleWkProcessPool];
Local Storage存在的問題
在查詢資料的過程中,發(fā)現(xiàn)了很多Local Storage的缺陷,有一篇關于Local Storage的論文可以參考。有以下幾點:
- 不要用Local Storage來做持久化存儲,在iOS中,出現(xiàn)存儲空間緊張時,它會被系統(tǒng)清理掉;
- 不要用Local Storage來存大量數(shù)據(jù),它的讀寫效率很低下,因為它需要序列化/反序列化;
- 大小限制為5M
webview 和 iframe 有什么區(qū)別?
webview是網(wǎng)頁的原生載體,用于在原生環(huán)境中加載一個頁面,iframe是網(wǎng)頁的html載體,用于在網(wǎng)頁中加載一個頁面