2023年6月21日发(作者:)

详解iOSwebview加载时序和缓存问题总结iOS webView的加载时序UIWebView加载顺序:- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSLog(@"开始请求webview:%@",veString); return YES;} - (void)webViewDidStartLoad:(UIWebView *)webView { NSLog(@"开始加载webview");

}- (void)webViewDidFinishLoad:(UIWebView *)webView {

NSLog(@"结束加载webview");

}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(nonnull NSError *)error {    NSLog(@"webView加载失败"); }加载的结果:-----------------显⽰开始加载html CSS js 和图⽚资源等(JS引擎单线程顺序执⾏)---------------2017-04-27 08:53:01.069 H5页⾯调试[1273:150877] 结束加载webview WKWebView加载时序:- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSLog(@"webview开始请求"); decisionHandler(WKNavigationActionPolicyAllow);}- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { NSLog(@"webView开始加载");}- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler { NSLog(@"webview开始收到响应"); decisionHandler(WKNavigationResponsePolicyAllow);}-----------------显⽰开始加载html CSS js 和图⽚资源等(JS引擎单线程顺序执⾏)---------------- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation { NSLog(@"1");}- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { NSLog(@"webview结束加载内容");}- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{ NSLog(@"webview加载失败");}- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{ NSLog(@"开始重定向的函数");}- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{ NSLog(@"2"); completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);}iOS webView加载html5缓存1.加载html5的过程每次加载⼀个HTML5页⾯,都会有较多的请求。除了HTML主URL⾃⾝的请求外,HTML外部引⽤的JS、CSS、字体⽂件、图⽚都是⼀个独⽴的HTTP请求,每⼀个请求都串⾏的(可能有连接复⽤)。2.设置清除html5页⾯缓存html5端设置meta标签:复制代码 代码如下:ios:设置加载的⽹络请求不采⽤本地缓存和远程缓存PS:设置上⾯的只是紧紧可以保证html⽂件每次从服务器中获取,不从缓存⽂件中拿,⽽对于外联CSS JS图⽚等⽂件仍旧是从缓存中获取的;3.设置css JS⽂件不从缓存中读取通过添加版本号的和随机数的⽅法,保证每次加载JS CSS连接都是最新的,通常的做法是添加⼀个版本号,在每次更新了JS CSS时给版本号+1;保证没有更新时采⽤缓存⽂件有更新可以从服务中获取;解决⽅法1、随机数法⽅法⼀:( " 其中 ver=113 的 113就是版本号这样真正做到了应该缓存的时候缓存静态⽂件,当版本有更新的时候从获取最新的版本,并更新缓存。对于图像 来有效利⽤和更新缓存.清除缓存⽂件- (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]; }}关于保存在沙盒中的缓存⽂件如下图:5.针对UIWebView出现的内存泄漏⽅法(⽹上) - (void)webViewDidFinishLoad:(UIWebView *)webView { //防⽌内存泄漏 [[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:经测试好像没什么卵⽤,先放在这⾥反正写了也没什么坏处确定1.如果没有CDN缓存影响;每次杀死APP后重新进⼊,第⼀次加载webview,都会加载全部的数据资源(外联js,外联css,图⽚等)退出去后,如果在没有更新js,css内容时,默认只会加载html内容,PS:html中的内容 在每次加载webView中都会从服务器中更新⼀下;2.如果js css后⾯都添加了版本号,那么在每次更新版本号时,或者说资源链接变化时,webView⼀定会重新加载新的内容;如下图疑问?1.经测试发现,JS CSS没有加版本号,更新JS CSS的内容有时候也会及时从服务器中更新获取,⼤多数时候⼜不会更新;不知道是不是跟web服务器的缓存策略有关,还是⽂件超期了?还是CDN缓存有关?以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。

2023年6月21日发(作者:)

详解iOSwebview加载时序和缓存问题总结iOS webView的加载时序UIWebView加载顺序:- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType { NSLog(@"开始请求webview:%@",veString); return YES;} - (void)webViewDidStartLoad:(UIWebView *)webView { NSLog(@"开始加载webview");

}- (void)webViewDidFinishLoad:(UIWebView *)webView {

NSLog(@"结束加载webview");

}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(nonnull NSError *)error {    NSLog(@"webView加载失败"); }加载的结果:-----------------显⽰开始加载html CSS js 和图⽚资源等(JS引擎单线程顺序执⾏)---------------2017-04-27 08:53:01.069 H5页⾯调试[1273:150877] 结束加载webview WKWebView加载时序:- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler { NSLog(@"webview开始请求"); decisionHandler(WKNavigationActionPolicyAllow);}- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation { NSLog(@"webView开始加载");}- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler { NSLog(@"webview开始收到响应"); decisionHandler(WKNavigationResponsePolicyAllow);}-----------------显⽰开始加载html CSS js 和图⽚资源等(JS引擎单线程顺序执⾏)---------------- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation { NSLog(@"1");}- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation { NSLog(@"webview结束加载内容");}- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(WKNavigation *)navigation withError:(NSError *)error{ NSLog(@"webview加载失败");}- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation{ NSLog(@"开始重定向的函数");}- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential *))completionHandler{ NSLog(@"2"); completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, nil);}iOS webView加载html5缓存1.加载html5的过程每次加载⼀个HTML5页⾯,都会有较多的请求。除了HTML主URL⾃⾝的请求外,HTML外部引⽤的JS、CSS、字体⽂件、图⽚都是⼀个独⽴的HTTP请求,每⼀个请求都串⾏的(可能有连接复⽤)。2.设置清除html5页⾯缓存html5端设置meta标签:复制代码 代码如下:ios:设置加载的⽹络请求不采⽤本地缓存和远程缓存PS:设置上⾯的只是紧紧可以保证html⽂件每次从服务器中获取,不从缓存⽂件中拿,⽽对于外联CSS JS图⽚等⽂件仍旧是从缓存中获取的;3.设置css JS⽂件不从缓存中读取通过添加版本号的和随机数的⽅法,保证每次加载JS CSS连接都是最新的,通常的做法是添加⼀个版本号,在每次更新了JS CSS时给版本号+1;保证没有更新时采⽤缓存⽂件有更新可以从服务中获取;解决⽅法1、随机数法⽅法⼀:( " 其中 ver=113 的 113就是版本号这样真正做到了应该缓存的时候缓存静态⽂件,当版本有更新的时候从获取最新的版本,并更新缓存。对于图像 来有效利⽤和更新缓存.清除缓存⽂件- (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]; }}关于保存在沙盒中的缓存⽂件如下图:5.针对UIWebView出现的内存泄漏⽅法(⽹上) - (void)webViewDidFinishLoad:(UIWebView *)webView { //防⽌内存泄漏 [[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:经测试好像没什么卵⽤,先放在这⾥反正写了也没什么坏处确定1.如果没有CDN缓存影响;每次杀死APP后重新进⼊,第⼀次加载webview,都会加载全部的数据资源(外联js,外联css,图⽚等)退出去后,如果在没有更新js,css内容时,默认只会加载html内容,PS:html中的内容 在每次加载webView中都会从服务器中更新⼀下;2.如果js css后⾯都添加了版本号,那么在每次更新版本号时,或者说资源链接变化时,webView⼀定会重新加载新的内容;如下图疑问?1.经测试发现,JS CSS没有加版本号,更新JS CSS的内容有时候也会及时从服务器中更新获取,⼤多数时候⼜不会更新;不知道是不是跟web服务器的缓存策略有关,还是⽂件超期了?还是CDN缓存有关?以上就是本⽂的全部内容,希望对⼤家的学习有所帮助,也希望⼤家多多⽀持。