1.在appdelegate中,- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary*)launchOptions 中添加代码
NSURLCache *urlCache = [[NSURLCache alloc] initWithMemoryCapacity:4 * 1024 * 1024 diskCapacity:20 * 1024 * 1024 diskPath:nil];
[NSURLCache setSharedURLCache:urlCache];
2.在wkwebview中加载页面时,
NSURL*url = [NSURLURLWithString:urlStr];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringCacheData timeoutInterval:15];
NSDictionary*cachedHeaders = [[NSUserDefaultsstandardUserDefaults]objectForKey:@"urlHeaderFields"];
//设置request headers (带上上次的请求头下面两参数一种就可以,也可以两个都带上)
if(cachedHeaders) {
NSString*etag = [cachedHeadersobjectForKey:@"Etag"];
if(etag) {
[requestsetValue:etagforHTTPHeaderField:@"If-None-Match"];
}
NSString*lastModified = [cachedHeadersobjectForKey:@"Last-Modified"];
if(lastModified) {
[requestsetValue:lastModifiedforHTTPHeaderField:@"If-Modified-Since"];
}
}
[[[NSURLSessionsharedSession]dataTaskWithRequest:requestcompletionHandler:^(NSData*_Nullabledata,NSURLResponse*_Nullableresponse,NSError*_Nullableerror) {
NSHTTPURLResponse*httpResponse = (NSHTTPURLResponse*)response;
NSLog(@"httpResponse == %@", httpResponse);
// 根据statusCode设置缓存策略,304是无更改,200是有更改需要重新拉取
if(httpResponse.statusCode==304|| httpResponse.statusCode==0) {
[request setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
}else{
[request setCachePolicy:NSURLRequestUseProtocolCachePolicy];
[USER_DEFAULT setObject:httpResponse.allHeaderFieldsforKey:@"urlHeaderFields"];
}
dispatch_async(dispatch_get_main_queue(), ^{
[self.contentWebloadRequest:request];
});
}]resume];
这里这样设置urlHeaderFields是因为前端发版,每一个url请求的Last-Modified都会改变。如果不是的话可以写成[USER_DEFAULT setObject:httpResponse.allHeaderFields forKey:urlStr];
ps:
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];
[self.contentWeb loadRequest:request];
这是简易版。但这样请求的话,会在前端发版的时候会多次加载文件,例如css和js
可以用Charles来抓取看请求信息。
请大神们指正!!!