詳解iOS webview加載時(shí)序和緩存問題總結(jié)
iOS webView的加載時(shí)序
UIWebView加載順序:
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
NSLog(@"開始請(qǐng)求webview:%@",request.URL.relativeString);
return YES;
}
- (void)webViewDidStartLoad:(UIWebView *)webView {
NSLog(@"開始加載webview");
}
- (void)webViewDidFinishLoad:(UIWebView *)webView {
NSLog(@"結(jié)束加載webview");
}
- (void)webView:(UIWebView *)webView didFailLoadWithError:(nonnull NSError *)error {
NSLog(@"webView加載失敗");
}
加載的結(jié)果:
2017-04-27 08:53:00.535 H5頁面調(diào)試[1273:150877] 開始請(qǐng)求webview:http://xxxx/index1.html
2017-04-27 08:53:00.537 H5頁面調(diào)試[1273:150877] 開始加載webview
-----------------顯示開始加載html CSS js 和圖片資源等(JS引擎單線程順序執(zhí)行)---------------
2017-04-27 08:53:01.069 H5頁面調(diào)試[1273:150877] 結(jié)束加載webview
WKWebView加載時(shí)序:
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSLog(@"webview開始請(qǐng)求");
decisionHandler(WKNavigationActionPolicyAllow);
}
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
NSLog(@"webView開始加載");
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler {
NSLog(@"webview開始收到響應(yīng)");
decisionHandler(WKNavigationResponsePolicyAllow);
}
-----------------顯示開始加載html CSS js 和圖片資源等(JS引擎單線程順序執(zhí)行)---------------
- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
NSLog(@"1");
}
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
NSLog(@"webview結(jié)束加載內(nèi)容");
}
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{
NSLog(@"webview加載失敗");
}
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{
NSLog(@"開始重定向的函數(shù)");
}
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler
{
NSLog(@"2");
completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);
}
iOS webView加載html5緩存
1.加載html5的過程
每次加載一個(gè)HTML5頁面,都會(huì)有較多的請(qǐng)求。除了HTML主URL自身的請(qǐng)求外,HTML外部引用的JS、CSS、字體文件、圖片都是一個(gè)獨(dú)立的HTTP請(qǐng)求,每一個(gè)請(qǐng)求都串行的(可能有連接復(fù)用)。
2.設(shè)置清除html5頁面緩存
html5端設(shè)置meta標(biāo)簽:
<meta http-equiv="Pragma" content="no-cache" /><meta http-equiv="Cache-Control" content="no-cache" /><meta http-equiv="Expires" content="0" />
ios:設(shè)置加載的網(wǎng)絡(luò)請(qǐng)求不采用本地緩存和遠(yuǎn)程緩存

PS:設(shè)置上面的只是緊緊可以保證html文件每次從服務(wù)器中獲取,不從緩存文件中拿,而對(duì)于外聯(lián)CSS JS圖片等文件仍舊是從緩存中獲取的;
3.設(shè)置css JS文件不從緩存中讀取
通過添加版本號(hào)的和隨機(jī)數(shù)的方法,保證每次加載JS CSS連接都是最新的,通常的做法是添加一個(gè)版本號(hào),在每次更新了JS CSS時(shí)給版本號(hào)+1;保證沒有更新時(shí)采用緩存文件
有更新可以從服務(wù)中獲??;
解決方法
1、隨機(jī)數(shù)法
方法一:
document.write( " <script src='test.js?rnd= " + Math.random() + " '></s " + " cript> " )
方法二:
var js = document.createElement( " script " ) js.src = " test.js " + Math.random() document.body.appendChild(js)
這樣采用隨機(jī)數(shù)的話, js文件將永遠(yuǎn)得不到緩存,每次都必須重新從服務(wù)器加載,即使沒有任何更改。
大家如果經(jīng)常上國(guó)外網(wǎng)站的話,可以看到他們通常采用這樣的方式來解決:
<script src="test.js?ver=113"></script>
其中 ver=113 的 113就是版本號(hào)
這樣真正做到了應(yīng)該緩存的時(shí)候緩存靜態(tài)文件,當(dāng)版本有更新的時(shí)候從獲取最新的版本,并更新緩存。
對(duì)于圖像 <img src="test.jps?ver=版本號(hào)"> 來有效利用和更新緩存.
4.iOS清除緩存文件
- (void)removeWebCache{
if ([[UIDevice currentDevice].systemVersion floatValue] >= 9.0) {
NSSet *websiteDataTypes= [NSSet setWithArray:@[
WKWebsiteDataTypeDiskCache,
//WKWebsiteDataTypeOfflineWebApplication
WKWebsiteDataTypeMemoryCache,
//WKWebsiteDataTypeLocal
WKWebsiteDataTypeCookies,
//WKWebsiteDataTypeSessionStorage,
//WKWebsiteDataTypeIndexedDBDatabases,
//WKWebsiteDataTypeWebSQLDatabases
]];
// All kinds of data
//NSSet *websiteDataTypes = [WKWebsiteDataStore allWebsiteDataTypes];
NSDate *dateFrom = [NSDate dateWithTimeIntervalSince1970:0];
[[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:websiteDataTypes modifiedSince:dateFrom completionHandler:^{
}];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
} else {
//先刪除cookie
NSHTTPCookie *cookie;
NSHTTPCookieStorage *storage = [NSHTTPCookieStorage sharedHTTPCookieStorage];
for (cookie in [storage cookies])
{
[storage deleteCookie:cookie];
}
NSString *libraryDir = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *bundleId = [[[NSBundle mainBundle] infoDictionary]
objectForKey:@"CFBundleIdentifier"];
NSString *webkitFolderInLib = [NSString stringWithFormat:@"%@/WebKit",libraryDir];
NSString *webKitFolderInCaches = [NSString
stringWithFormat:@"%@/Caches/%@/WebKit",libraryDir,bundleId];
NSString *webKitFolderInCachesfs = [NSString
stringWithFormat:@"%@/Caches/%@/fsCachedData",libraryDir,bundleId];
NSError *error;
/* iOS8.0 WebView Cache的存放路徑 */
[[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCaches error:&error];
[[NSFileManager defaultManager] removeItemAtPath:webkitFolderInLib error:nil];
/* iOS7.0 WebView Cache的存放路徑 */
[[NSFileManager defaultManager] removeItemAtPath:webKitFolderInCachesfs error:&error];
NSString *cookiesFolderPath = [libraryDir stringByAppendingString:@"/Cookies"];
[[NSFileManager defaultManager] removeItemAtPath:cookiesFolderPath error:&error];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
}
關(guān)于保存在沙盒中的緩存文件如下圖:


5.針對(duì)UIWebView出現(xiàn)的內(nèi)存泄漏方法(網(wǎng)上)
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
//防止內(nèi)存泄漏
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:@"WebKitCacheModelPreferenceKey"];
//本地webkit硬盤圖片的緩存;
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitDiskImageCacheEnabled"];//自己添加的,原文沒有提到。
//靜止webkit離線緩存
[[NSUserDefaults standardUserDefaults] setBool:NO forKey:@"WebKitOfflineWebApplicationCacheEnabled"];//自己添加的,,原文沒有提到。
[[NSUserDefaults standardUserDefaults] synchronize];
}
- (void)dealloc
{
[webView loadHTMLString:@"" baseURL:nil];
[webView stopLoading];
[webView removeFromSuperview];
webView = nil;
[[NSURLCache sharedURLCache] removeAllCachedResponses];
[[NSURLCache sharedURLCache] setDiskCapacity:0];
[[NSURLCache sharedURLCache] setMemoryCapacity:0];
NSLog(@"釋放了webview");
}
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{
int cacheSizeMemory = 4*1024*1024; // 4MB int
cacheSizeDisk = 32*1024*1024; // 32MB
NSURLCache *sharedCache = [[NSURLCache alloc] initWithMemoryCapacity:cacheSizeMemory diskCapacity:cacheSizeDisk diskPath:@"nsurlcache"];
[NSURLCache setSharedURLCache:sharedCache];
}
- (void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
PS:經(jīng)測(cè)試好像沒什么卵用,先放在這里反正寫了也沒什么壞處
確定
1.如果沒有CDN緩存影響;每次殺死APP后重新進(jìn)入,第一次加載webview,都會(huì)加載全部的數(shù)據(jù)資源(外聯(lián)js,外聯(lián)css,圖片等)退出去后,如果在沒有更新js,css內(nèi)容時(shí),默認(rèn)只會(huì)加載html內(nèi)容,PS:html中的內(nèi)容 在每次加載webView中都會(huì)從服務(wù)器中更新一下;
2.如果js css后面都添加了版本號(hào),那么在每次更新版本號(hào)時(shí),或者說資源鏈接變化時(shí),webView一定會(huì)重新加載新的內(nèi)容;如下圖
<script type="text/javascript" src="index1.js?v=1.0.0"></script>
疑問?
1.經(jīng)測(cè)試發(fā)現(xiàn),JS CSS沒有加版本號(hào),更新JS CSS的內(nèi)容有時(shí)候也會(huì)及時(shí)從服務(wù)器中更新獲取,大多數(shù)時(shí)候又不會(huì)更新;不知道是不是跟web服務(wù)器的緩存策略有關(guān),還是文件超期了?還是CDN緩存有關(guān)?
以上就是本文的全部?jī)?nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
Flutter?GetPageRoute實(shí)現(xiàn)嵌套導(dǎo)航學(xué)習(xí)
這篇文章主要為大家介紹了Flutter?GetPageRoute實(shí)現(xiàn)嵌套導(dǎo)航的示例學(xué)習(xí),有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2022-08-08
Objective-C的MKNetworkKit開發(fā)框架解析
這篇文章主要介紹了Objective-C的MKNetworkKit開發(fā)框架解析,MKNetworkKit是一個(gè)用于iOS開發(fā)的輕量級(jí)框架,需要的朋友可以參考下2015-11-11
IOS程序開發(fā)之禁止輸入表情符號(hào)實(shí)例代碼
如何禁止輸入表情符號(hào)呢?下面腳本之家小編給大家分享IOS程序開發(fā)之禁止輸入表情符號(hào)實(shí)例代碼,感興趣的朋友參考下吧2016-04-04
關(guān)于iOS中的各種顏色設(shè)置總結(jié)大全(推薦)
這篇文章主要給大家介紹了關(guān)于iOS中顏色設(shè)置的相關(guān)資料,其中包括導(dǎo)航欄、狀態(tài)欄、Tabbar、Button、TextField、AttributedString和通用部分的顏色設(shè)置方法示例,對(duì)大家具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起看看吧。2017-09-09
iOS框架AVFoundation實(shí)現(xiàn)相機(jī)拍照、錄制視頻
這篇文章主要為大家詳細(xì)介紹了iOS框架AVFoundation實(shí)現(xiàn)相機(jī)拍照、錄制視頻功能,具有一定的參考價(jià)值,感興趣的小伙伴們可以參考一下2018-05-05

