├── LICENSE ├── README.md ├── ZGWKWebCache ├── FileUtil.h ├── FileUtil.m ├── NSString+ZGExtension.h ├── NSString+ZGExtension.m ├── NSURLProtocol+WKWebView.h ├── NSURLProtocol+WKWebView.m ├── ZGCacheModel.h ├── ZGCacheModel.m ├── ZGURLProtocol.h ├── ZGURLProtocol.m ├── ZGWKWebViewCache.h └── ZGWKWebViewCache.m ├── ZGWKWebViewCache.xcodeproj ├── project.pbxproj ├── project.xcworkspace │ ├── contents.xcworkspacedata │ └── xcuserdata │ │ └── zhanggui.xcuserdatad │ │ └── UserInterfaceState.xcuserstate └── xcuserdata │ └── zhanggui.xcuserdatad │ ├── xcdebugger │ └── Breakpoints_v2.xcbkptlist │ └── xcschemes │ └── xcschememanagement.plist └── ZGWKWebViewCache ├── AppDelegate.h ├── AppDelegate.m ├── Assets.xcassets └── AppIcon.appiconset │ └── Contents.json ├── Base.lproj ├── LaunchScreen.storyboard └── Main.storyboard ├── Info.plist ├── ViewController.h ├── ViewController.m ├── ZGWKWebViewCache ├── FileUtil.h ├── FileUtil.m ├── NSString+ZGExtension.h ├── NSString+ZGExtension.m ├── NSURLProtocol+WKWebView.h ├── NSURLProtocol+WKWebView.m ├── ZGCacheModel.h ├── ZGCacheModel.m ├── ZGURLProtocol.h ├── ZGURLProtocol.m ├── ZGWKWebViewCache.h └── ZGWKWebViewCache.m └── main.m /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2017 Zhang Gui 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ZGWKWebViewCache 2 | iOS WKWebView cache 3 | -------------------------------------------------------------------------------- /ZGWKWebCache/FileUtil.h: -------------------------------------------------------------------------------- 1 | // 2 | // FileUtil.h 3 | // RongShu 4 | // 5 | // Created by zhanggui on 2017/11/9. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface FileUtil : NSObject 12 | 13 | 14 | @property (nonatomic,assign)BOOL debug; 15 | 16 | - (instancetype)init NS_UNAVAILABLE; 17 | 18 | + (instancetype)shared; 19 | 20 | 21 | - (void)write:(NSData *)data forKey:(NSString *)key; 22 | 23 | 24 | 25 | -(NSData *)readForKey:(NSString *)key; 26 | 27 | 28 | 29 | - (void)clearCacheFolder; 30 | @end 31 | -------------------------------------------------------------------------------- /ZGWKWebCache/FileUtil.m: -------------------------------------------------------------------------------- 1 | // 2 | // FileUtil.m 3 | // RongShu 4 | // 5 | // Created by zhanggui on 2017/11/9. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "FileUtil.h" 10 | 11 | #import "NSString+ZGExtension.h" 12 | static inline NSString * RSFileCacheDirectory() { 13 | static NSString * _fileDic; 14 | static dispatch_once_t onceToken; 15 | dispatch_once(&onceToken, ^{ 16 | _fileDic = NSSearchPathForDirectoriesInDomains( NSCachesDirectory, NSUserDomainMask, YES )[0]; 17 | }); 18 | return _fileDic; 19 | } 20 | 21 | static inline NSString *cachePathForKey(NSString *key) { 22 | NSString *fileName = [NSString SHA1FromString:key]; 23 | NSString *filePath = [RSFileCacheDirectory() stringByAppendingString:@"/ZGWebCaches"]; 24 | if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { 25 | [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil]; 26 | } 27 | return [[filePath stringByAppendingString:@"/"] stringByAppendingString:fileName]; 28 | } 29 | @interface FileUtil () 30 | 31 | @property (nonatomic,strong)NSCache *cache; 32 | 33 | 34 | 35 | @property (nonatomic,strong)dispatch_queue_t zgQueue; 36 | @end 37 | 38 | 39 | 40 | @implementation FileUtil 41 | 42 | 43 | + (instancetype)shared { 44 | static FileUtil *util = nil; 45 | static dispatch_once_t onceToken; 46 | dispatch_once(&onceToken, ^{ 47 | util = [[self alloc] init]; 48 | }); 49 | return util; 50 | } 51 | - (id)init { 52 | self = [super init]; 53 | if (self) { 54 | _debug = true; 55 | } 56 | return self; 57 | } 58 | - (void)clearCacheFolder { 59 | NSString *cacheFolder = [RSFileCacheDirectory() stringByAppendingString:@"/RSWebCaches"]; 60 | NSError *error; 61 | NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:cacheFolder error:&error]; 62 | if (error || !contents || contents.count<=0) { 63 | return; 64 | } 65 | for (NSString *fileName in contents) { 66 | NSString *path = [NSString stringWithFormat:@"/%@",fileName]; 67 | NSString *filePath = [cacheFolder stringByAppendingString:path]; 68 | BOOL bo = [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]; 69 | if (bo) { 70 | NSString *str = [NSString stringWithFormat:@"移除%@成功",filePath]; 71 | [self ZGLog:str]; 72 | } 73 | } 74 | 75 | } 76 | //内存 -> 文件系统 77 | - (NSData *)readForKey:(NSString *)key { 78 | if (!key) { 79 | return nil; 80 | } 81 | NSData *cacheData = [self.cache objectForKey:key]; 82 | if (cacheData) { 83 | NSString *str = [NSString stringWithFormat:@"从cache中读取%@",key]; 84 | [self ZGLog:str]; 85 | return cacheData; 86 | }else { 87 | NSString *str = [NSString stringWithFormat:@"从cache无法读取,从文件读取从cache中读取%@",key]; 88 | [self ZGLog:str]; 89 | NSString *filePath = cachePathForKey(key); 90 | NSData *fileData = [[NSFileManager defaultManager] contentsAtPath:filePath]; 91 | if (fileData) { 92 | [self.cache setObject:fileData forKey:key]; 93 | } 94 | return fileData; 95 | } 96 | return nil; 97 | } 98 | - (void)write:(NSData *)data forKey:(NSString *)key { 99 | NSString *filePath = cachePathForKey(key); 100 | NSURL *fileUrl = [NSURL fileURLWithPath:filePath]; 101 | [self.cache setObject:data forKey:key]; 102 | dispatch_async(self.zgQueue, ^{ 103 | BOOL boo = [[NSFileManager defaultManager] createFileAtPath:fileUrl.path contents:data attributes:nil]; 104 | if (boo) { 105 | NSString *str = [NSString stringWithFormat:@"创建%@成功",filePath]; 106 | [self ZGLog:str]; 107 | 108 | }else { 109 | NSString *str = [NSString stringWithFormat:@"创建%@失败",filePath]; 110 | [self ZGLog:str]; 111 | } 112 | }); 113 | } 114 | - (void)ZGLog:(NSString *)str { 115 | if (_debug) { 116 | NSLog(@"%@", str); 117 | } 118 | } 119 | - (dispatch_queue_t)zgQueue { 120 | if (!_zgQueue) { 121 | _zgQueue = dispatch_queue_create("com.zgCache.zgCache", DISPATCH_QUEUE_CONCURRENT); 122 | } 123 | return _zgQueue; 124 | } 125 | - (NSCache *)cache { 126 | if (!_cache) { 127 | _cache = [[NSCache alloc] init]; 128 | } 129 | return _cache; 130 | } 131 | @end 132 | -------------------------------------------------------------------------------- /ZGWKWebCache/NSString+ZGExtension.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSString+Extension.h 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface NSString (ZGExtension) 12 | 13 | /** 14 | SHA1 15 | 16 | @param string 要sha1的string 17 | @return 返回sha1后的str 18 | */ 19 | + (NSString *)SHA1FromString:(NSString *)string; 20 | @end 21 | -------------------------------------------------------------------------------- /ZGWKWebCache/NSString+ZGExtension.m: -------------------------------------------------------------------------------- 1 | // 2 | // NSString+Extension.m 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "NSString+ZGExtension.h" 10 | #import 11 | @implementation NSString (ZGExtension) 12 | 13 | #pragma mark - Hash methods 14 | + (NSString *)SHA1FromString:(NSString *)string { 15 | unsigned char digest[CC_SHA1_DIGEST_LENGTH]; 16 | 17 | NSData *stringBytes = [string dataUsingEncoding:NSUTF8StringEncoding]; 18 | 19 | if (CC_SHA1([stringBytes bytes], (CC_LONG)[stringBytes length], digest)) { 20 | 21 | NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; 22 | 23 | for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) { 24 | [output appendFormat:@"%02x", digest[i]]; 25 | } 26 | 27 | return output; 28 | } 29 | return nil; 30 | } 31 | @end 32 | -------------------------------------------------------------------------------- /ZGWKWebCache/NSURLProtocol+WKWebView.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLProtocol+WKWebView.h 3 | // ZGWKWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/22. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface NSURLProtocol (WKWebView) 12 | 13 | 14 | + (void)zg_registerScheme:(NSString *)scheme; 15 | 16 | 17 | + (void)zg_unregisterScheme:(NSString *)scheme; 18 | @end 19 | -------------------------------------------------------------------------------- /ZGWKWebCache/NSURLProtocol+WKWebView.m: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLProtocol+WKWebView.m 3 | // ZGWKWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/22. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "NSURLProtocol+WKWebView.h" 10 | #import 11 | 12 | 13 | FOUNDATION_STATIC_INLINE Class ContextControllerClass() { 14 | static Class cls; 15 | if (!cls) { 16 | cls = [[[WKWebView new] valueForKey:@"browsingContextController"] class]; 17 | } 18 | return cls; 19 | } 20 | FOUNDATION_STATIC_INLINE SEL RegisterSchemeSelector () { 21 | return NSSelectorFromString(@"registerSchemeForCustomProtocol:"); 22 | } 23 | FOUNDATION_STATIC_INLINE SEL UnregisterSchemeSelector () { 24 | return NSSelectorFromString(@"unregisterSchemeForCustomProtocol:"); 25 | } 26 | 27 | @implementation NSURLProtocol (WKWebView) 28 | 29 | + (void)zg_registerScheme:(NSString *)scheme { 30 | Class cls = ContextControllerClass(); 31 | SEL sel = RegisterSchemeSelector(); 32 | if ([(id)cls respondsToSelector:sel]) { 33 | #pragma clang diagnostic push 34 | #pragma clang diagnostic ignored "-Warc-performSelector-leaks" 35 | [(id)cls performSelector:sel withObject:scheme]; 36 | #pragma clang diagnostic pop 37 | } 38 | } 39 | + (void)zg_unregisterScheme:(NSString *)scheme { 40 | Class cls = ContextControllerClass(); 41 | SEL sel = UnregisterSchemeSelector(); 42 | if ([(id)cls respondsToSelector:sel]) { 43 | #pragma clang diagnostic push 44 | #pragma clang diagnostic ignored "-Warc-performSelector-leaks" 45 | [(id)cls performSelector:sel withObject:scheme]; 46 | #pragma clang diagnostic pop 47 | } 48 | } 49 | @end 50 | -------------------------------------------------------------------------------- /ZGWKWebCache/ZGCacheModel.h: -------------------------------------------------------------------------------- 1 | // 2 | // ZGCacheModel.h 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ZGCacheModel : NSObject 12 | 13 | /** 14 | mime 类型 15 | */ 16 | @property (nonatomic,strong)NSString *MIMEType; 17 | 18 | 19 | /** 20 | 缓存数据 21 | */ 22 | @property (nonatomic,strong)NSData *data; 23 | @end 24 | -------------------------------------------------------------------------------- /ZGWKWebCache/ZGCacheModel.m: -------------------------------------------------------------------------------- 1 | // 2 | // ZGCacheModel.m 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "ZGCacheModel.h" 10 | 11 | @implementation ZGCacheModel 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /ZGWKWebCache/ZGURLProtocol.h: -------------------------------------------------------------------------------- 1 | // 2 | // ZGURLProtocol.h 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ZGURLProtocol : NSURLProtocol 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /ZGWKWebCache/ZGURLProtocol.m: -------------------------------------------------------------------------------- 1 | // 2 | // ZGURLProtocol.m 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "ZGURLProtocol.h" 10 | #import "ZGCacheModel.h" 11 | #import "ZGWKWebViewCache.h" 12 | static NSString * const ZGURLProtocolKey = @"zgPKey"; 13 | 14 | @interface ZGURLProtocol() 15 | 16 | /** 17 | 请求的数据 18 | */ 19 | @property (nonatomic,strong)NSMutableData *responseData; 20 | 21 | /** 22 | task 23 | */ 24 | @property (nonatomic,strong)NSURLSessionDataTask *task; 25 | 26 | @property (nonatomic,strong)NSString *responseMIMEType; 27 | @end 28 | 29 | @implementation ZGURLProtocol 30 | 31 | + (BOOL)canInitWithRequest:(NSURLRequest *)request { 32 | NSString *scheme = [[request URL] scheme]; 33 | NSLog(@"1111%@",request.URL.absoluteString); 34 | if ([scheme caseInsensitiveCompare:@"http"] == NSOrderedSame || [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame) { //只缓存http和https的请求 35 | NSString *str = request.URL.path; 36 | if ([self cacheTypeWithStr:str] && ![NSURLProtocol propertyForKey:ZGURLProtocolKey inRequest:request]) { 37 | return YES; 38 | } 39 | } 40 | return NO; 41 | } 42 | + (BOOL)cacheTypeWithStr:(NSString *)str { 43 | if ([[[ZGWKWebViewCache sharedWebViewCache] cacheArr] containsObject:@(CacheTypeJS)] && [str hasSuffix:@".js"]) { 44 | return YES; 45 | } 46 | if ([[[ZGWKWebViewCache sharedWebViewCache] cacheArr] containsObject:@(CacheTypeImage)] && [self ifImageType:str]) { 47 | return YES; 48 | } 49 | if ([[[ZGWKWebViewCache sharedWebViewCache] cacheArr] containsObject:@(CacheTypeCSS)] && [str hasSuffix:@".css"]) { 50 | return YES; 51 | } 52 | if ([[[ZGWKWebViewCache sharedWebViewCache] cacheArr] containsObject:@(CacheTypeHTML)] && [str hasSuffix:@".html"]) { 53 | return YES; 54 | } 55 | return NO; 56 | } 57 | /** 58 | 判断是否值js 59 | 60 | @param urlStr 资源地址,这里暂时只判断了一下js 61 | @return YES表示是js,NO表示不是js 62 | */ 63 | + (BOOL)ifJSType:(NSString *)urlStr { 64 | if ([urlStr hasSuffix:@".js"]) { 65 | return YES; 66 | } 67 | return NO; 68 | } 69 | /** 70 | 判断将要请求的资源是否是图片 71 | 72 | @param urlStr 资源地址,这里暂时只判断了一下png/jpg/gif/jpeg四种格式 73 | @return YES表示是图片,NO表示不是图片 74 | */ 75 | + (BOOL)ifImageType:(NSString *)urlStr { 76 | if ([urlStr hasSuffix:@".png"] || 77 | [urlStr hasSuffix:@".jpg"] || 78 | [urlStr hasSuffix:@".gif"] || 79 | [urlStr hasSuffix:@".jpeg"]) { 80 | return YES; 81 | } 82 | return NO; 83 | } 84 | + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { 85 | //这里可以进行重定向操作,重写request, 86 | return request; 87 | } 88 | //这里请求是否的等价于缓存 89 | + (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b { 90 | return [super requestIsCacheEquivalent:a toRequest:b]; 91 | } 92 | //开始请求 93 | - (void)startLoading { 94 | NSMutableURLRequest *mutableRequest = [[self request] mutableCopy]; 95 | [NSURLProtocol setProperty:@YES forKey:ZGURLProtocolKey inRequest:mutableRequest]; 96 | ZGCacheModel *model = [[ZGWKWebViewCache sharedWebViewCache] getCacheDataByKey:self.request.URL.absoluteString]; 97 | 98 | if (model.data && model.MIMEType) { 99 | NSURLResponse *response = [[NSURLResponse alloc] initWithURL:self.request.URL MIMEType:model.MIMEType expectedContentLength:model.data.length textEncodingName:nil]; 100 | [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed]; 101 | [self.client URLProtocol:self didLoadData:model.data]; 102 | [self.client URLProtocolDidFinishLoading:self]; 103 | }else { 104 | NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil]; 105 | self.task = [session dataTaskWithRequest:self.request]; 106 | [self.task resume]; 107 | } 108 | } 109 | - (void)stopLoading { 110 | if (self.task) { 111 | [self.task cancel]; 112 | } 113 | } 114 | 115 | #pragma mark - NSURLConnectionDelegate 116 | - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { 117 | self.responseData = [NSMutableData data]; 118 | [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed]; 119 | 120 | completionHandler(NSURLSessionResponseAllow); 121 | } 122 | - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { 123 | [self.responseData appendData:data]; 124 | 125 | 126 | [[self client] URLProtocol:self didLoadData:data]; 127 | } 128 | - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { 129 | if (error) { 130 | [self.client URLProtocolDidFinishLoading:self]; 131 | return; 132 | } 133 | ZGCacheModel *model = [ZGCacheModel new]; 134 | model.data = self.responseData; 135 | model.MIMEType = task.response.MIMEType; 136 | 137 | [self setMiType:model.MIMEType withKey:[self.request.URL path]];//userdefault存储MIMEtype 138 | [[ZGWKWebViewCache sharedWebViewCache] setCacheWithKey:self.request.URL.absoluteString value:model]; 139 | [self.client URLProtocolDidFinishLoading:self]; 140 | } 141 | /** 142 | 将类型和key存储到一个字典里面,然后 143 | 144 | @param mimeType mime类型 145 | @param urlKey url的key 146 | */ 147 | - (void)setMiType:(NSString *)mimeType withKey:(NSString *)urlKey { 148 | NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:URLMIMETYPE]; 149 | 150 | if (!dic) { 151 | dic = [NSMutableDictionary dictionary]; 152 | } 153 | NSMutableDictionary *muDic = [[NSMutableDictionary alloc] initWithDictionary:dic]; 154 | [muDic setValue:mimeType forKey:urlKey]; 155 | [[NSUserDefaults standardUserDefaults] setObject:muDic forKey:URLMIMETYPE]; 156 | [[NSUserDefaults standardUserDefaults] synchronize]; 157 | } 158 | @end 159 | -------------------------------------------------------------------------------- /ZGWKWebCache/ZGWKWebViewCache.h: -------------------------------------------------------------------------------- 1 | // 2 | // ZGUIWebViewCache.h 3 | // ZGUIWebViewCache 4 | //使用过程中只需要关注该类即可,其他类无需关注 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "ZGCacheModel.h" 11 | 12 | extern NSString *const URLMIMETYPE; 13 | 14 | 15 | typedef NS_ENUM(NSInteger,CacheType) { 16 | CacheTypeImage = 4, 17 | CacheTypeJS, 18 | CacheTypeCSS, 19 | CacheTypeHTML 20 | }; 21 | @interface ZGWKWebViewCache : NSObject 22 | 23 | 24 | /** 25 | 初始化web cache该方法可以直接在application:didFinishLaunchingWithOptions中调用 26 | @param arr 缓存类型,CacheType 27 | */ 28 | - (void)initWebCacheWithCacheTypes:(NSArray *)arr; 29 | 30 | 31 | 32 | 33 | 34 | +(instancetype)sharedWebViewCache; 35 | 36 | 37 | - (instancetype)init NS_UNAVAILABLE; 38 | 39 | 40 | 41 | /** 42 | 注册cache 43 | */ 44 | + (void)registerSchemeCache; 45 | 46 | /** 47 | 不注册cache 48 | */ 49 | + (void)unRegisterSchemeCache; 50 | 51 | /** 52 | 得到缓存的数据 53 | 54 | @param cacheKey 缓存key 55 | @return 返回缓存model 56 | */ 57 | - (ZGCacheModel *)getCacheDataByKey:(NSString *)cacheKey; 58 | 59 | /** 60 | 设置离线缓存,根据需求缓存,如果你的js有版本号,那么如有更新,缓存key便会和原有key不一致,达到更新效果。如果相同的链接内容更改则无法实现即时更新。 61 | 62 | @param key 缓存key 63 | @param model 缓存model 64 | */ 65 | - (void)setCacheWithKey:(NSString *)key value:(ZGCacheModel *)model; 66 | 67 | 68 | /** 69 | 清除缓存,自己在合适的地方调用,比如清除缓存按钮点击 70 | */ 71 | - (void)clearZGCache; 72 | 73 | - (NSArray *)cacheArr; 74 | /** 75 | 清除缓存 76 | 77 | @param day 天数,例如7天,7天后会自动清除所有缓存,该方法可以直接在application:didFinishLaunchingWithOptions中调用 78 | */ 79 | - (void)clearCacheWithInvalidDays:(NSInteger)day; 80 | 81 | 82 | /** 83 | 设置debug模式,是否打印日志,默认为NO,上线请设置为NO 84 | 85 | @param boo YES表示开启debug模式,NO表示关闭debugM模式 86 | */ 87 | - (void)setDebugModel:(BOOL)boo; 88 | 89 | @end 90 | -------------------------------------------------------------------------------- /ZGWKWebCache/ZGWKWebViewCache.m: -------------------------------------------------------------------------------- 1 | // 2 | // ZGUIWebViewCache.m 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "ZGWKWebViewCache.h" 10 | #import "ZGURLProtocol.h" 11 | #import "FileUtil.h" 12 | #import "NSURLProtocol+WKWebView.h" 13 | NSString * const URLMIMETYPE = @"url_mime_type"; 14 | 15 | 16 | static NSString * const CacheLiveTimeKey = @"CacheLiveTimeKey"; 17 | 18 | static NSInteger const CacheLiveDate = 7; //cache默认缓存时间为7天,7天清理一次缓存 19 | 20 | @interface ZGWKWebViewCache() 21 | @property (nonatomic,assign)BOOL debug; 22 | 23 | 24 | @property (nonatomic,strong)NSArray *cacheTypeArr; 25 | @end 26 | 27 | @implementation ZGWKWebViewCache 28 | 29 | + (instancetype)sharedWebViewCache { 30 | static ZGWKWebViewCache *ch = nil; 31 | static dispatch_once_t onceToken; 32 | dispatch_once(&onceToken, ^{ 33 | ch = [[self alloc] init]; 34 | }); 35 | return ch; 36 | } 37 | - (NSArray *)cacheArr { 38 | return _cacheTypeArr; 39 | } 40 | - (void)initWebCacheWithCacheTypes:(NSArray *)arr { 41 | [NSURLProtocol registerClass:[ZGURLProtocol class]]; 42 | _cacheTypeArr =arr; 43 | } 44 | 45 | - (ZGCacheModel *)getCacheDataByKey:(NSString *)cacheKey { 46 | ZGCacheModel *model = [ZGCacheModel new]; 47 | 48 | FileUtil *util = [FileUtil shared]; 49 | 50 | model.data = [util readForKey:cacheKey]; 51 | if (model.data) { 52 | model.MIMEType = [self getMIMETypeFromKey:cacheKey]; 53 | } 54 | return model; 55 | } 56 | - (void)setCacheWithKey:(NSString *)key value:(ZGCacheModel *)model { 57 | FileUtil *util = [FileUtil shared]; 58 | [util write:model.data forKey:key]; 59 | } 60 | - (void)clearZGCache { 61 | 62 | [[FileUtil shared] clearCacheFolder]; //清除缓存的文件 63 | 64 | [[NSUserDefaults standardUserDefaults] removeObjectForKey:URLMIMETYPE]; //清除mime类型s 65 | [[NSUserDefaults standardUserDefaults] removeObjectForKey:CacheLiveTimeKey]; 66 | 67 | } 68 | - (void)clearCacheWithInvalidDays:(NSInteger)day { 69 | NSDate *originTime = [[NSUserDefaults standardUserDefaults] objectForKey:CacheLiveTimeKey]; //存取当前时间 70 | if (!originTime) { 71 | originTime = [self beijingTime]; 72 | [[NSUserDefaults standardUserDefaults] setObject:originTime forKey:CacheLiveTimeKey]; 73 | } 74 | if (day<=0) { 75 | day = CacheLiveDate; 76 | } 77 | NSDate *sevenTime = [originTime dateByAddingTimeInterval:24*60*60*day]; 78 | 79 | NSDate *currentDateTime = [self beijingTime]; 80 | NSComparisonResult result = [currentDateTime compare:sevenTime]; 81 | 82 | if (result == NSOrderedDescending) { //时间超过设定的时间 83 | [self clearZGCache]; 84 | } 85 | } 86 | - (void)setDebugModel:(BOOL)boo { 87 | 88 | FileUtil *util = [FileUtil shared]; 89 | util.debug = boo; 90 | _debug = boo; 91 | 92 | } 93 | + (void)registerSchemeCache { 94 | [NSURLProtocol zg_registerScheme:@"http"]; 95 | [NSURLProtocol zg_registerScheme:@"https"]; 96 | } 97 | + (void)unRegisterSchemeCache { 98 | [NSURLProtocol zg_unregisterScheme:@"http"]; 99 | [NSURLProtocol zg_unregisterScheme:@"https"]; 100 | } 101 | #pragma mark - private method 102 | //拿到当前北京时间 103 | - (NSDate *)beijingTime { 104 | NSDate *date = [NSDate date]; 105 | NSTimeInterval inter = [[NSTimeZone systemTimeZone] secondsFromGMT]; 106 | return [date dateByAddingTimeInterval:inter]; 107 | } 108 | /** 109 | 得到MIME类型 110 | 111 | @param cacheKey 缓存key 112 | @return MIME类型 113 | */ 114 | - (NSString *)getMIMETypeFromKey:(NSString *)cacheKey { 115 | NSURL *url = [NSURL URLWithString:cacheKey]; 116 | NSString *keyValue = [url path]; 117 | 118 | NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:URLMIMETYPE]; 119 | NSString *mimeType = [dic objectForKey:keyValue]; 120 | 121 | if (mimeType) { 122 | return mimeType; 123 | } 124 | return nil; 125 | } 126 | 127 | @end 128 | -------------------------------------------------------------------------------- /ZGWKWebViewCache.xcodeproj/project.pbxproj: -------------------------------------------------------------------------------- 1 | // !$*UTF8*$! 2 | { 3 | archiveVersion = 1; 4 | classes = { 5 | }; 6 | objectVersion = 48; 7 | objects = { 8 | 9 | /* Begin PBXBuildFile section */ 10 | 56722E021FC2D1A0000198CB /* AppDelegate.m in Sources */ = {isa = PBXBuildFile; fileRef = 56722E011FC2D1A0000198CB /* AppDelegate.m */; }; 11 | 56722E051FC2D1A0000198CB /* ViewController.m in Sources */ = {isa = PBXBuildFile; fileRef = 56722E041FC2D1A0000198CB /* ViewController.m */; }; 12 | 56722E081FC2D1A0000198CB /* Main.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56722E061FC2D1A0000198CB /* Main.storyboard */; }; 13 | 56722E0A1FC2D1A0000198CB /* Assets.xcassets in Resources */ = {isa = PBXBuildFile; fileRef = 56722E091FC2D1A0000198CB /* Assets.xcassets */; }; 14 | 56722E0D1FC2D1A0000198CB /* LaunchScreen.storyboard in Resources */ = {isa = PBXBuildFile; fileRef = 56722E0B1FC2D1A0000198CB /* LaunchScreen.storyboard */; }; 15 | 56722E101FC2D1A0000198CB /* main.m in Sources */ = {isa = PBXBuildFile; fileRef = 56722E0F1FC2D1A0000198CB /* main.m */; }; 16 | 5682AEE51FC563E4001B31AD /* NSString+ZGExtension.m in Sources */ = {isa = PBXBuildFile; fileRef = 5682AEDB1FC563E3001B31AD /* NSString+ZGExtension.m */; }; 17 | 5682AEE61FC563E4001B31AD /* ZGWKWebViewCache.m in Sources */ = {isa = PBXBuildFile; fileRef = 5682AEDC1FC563E3001B31AD /* ZGWKWebViewCache.m */; }; 18 | 5682AEE71FC563E4001B31AD /* FileUtil.m in Sources */ = {isa = PBXBuildFile; fileRef = 5682AEE01FC563E3001B31AD /* FileUtil.m */; }; 19 | 5682AEE81FC563E4001B31AD /* ZGCacheModel.m in Sources */ = {isa = PBXBuildFile; fileRef = 5682AEE11FC563E3001B31AD /* ZGCacheModel.m */; }; 20 | 5682AEE91FC563E4001B31AD /* ZGURLProtocol.m in Sources */ = {isa = PBXBuildFile; fileRef = 5682AEE21FC563E3001B31AD /* ZGURLProtocol.m */; }; 21 | 5682AEEF1FC56583001B31AD /* NSURLProtocol+WKWebView.m in Sources */ = {isa = PBXBuildFile; fileRef = 5682AEEE1FC56583001B31AD /* NSURLProtocol+WKWebView.m */; }; 22 | /* End PBXBuildFile section */ 23 | 24 | /* Begin PBXFileReference section */ 25 | 56722DFD1FC2D1A0000198CB /* ZGWKWebViewCache.app */ = {isa = PBXFileReference; explicitFileType = wrapper.application; includeInIndex = 0; path = ZGWKWebViewCache.app; sourceTree = BUILT_PRODUCTS_DIR; }; 26 | 56722E001FC2D1A0000198CB /* AppDelegate.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = AppDelegate.h; sourceTree = ""; }; 27 | 56722E011FC2D1A0000198CB /* AppDelegate.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = AppDelegate.m; sourceTree = ""; }; 28 | 56722E031FC2D1A0000198CB /* ViewController.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = ViewController.h; sourceTree = ""; }; 29 | 56722E041FC2D1A0000198CB /* ViewController.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = ViewController.m; sourceTree = ""; }; 30 | 56722E071FC2D1A0000198CB /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/Main.storyboard; sourceTree = ""; }; 31 | 56722E091FC2D1A0000198CB /* Assets.xcassets */ = {isa = PBXFileReference; lastKnownFileType = folder.assetcatalog; path = Assets.xcassets; sourceTree = ""; }; 32 | 56722E0C1FC2D1A0000198CB /* Base */ = {isa = PBXFileReference; lastKnownFileType = file.storyboard; name = Base; path = Base.lproj/LaunchScreen.storyboard; sourceTree = ""; }; 33 | 56722E0E1FC2D1A0000198CB /* Info.plist */ = {isa = PBXFileReference; lastKnownFileType = text.plist.xml; path = Info.plist; sourceTree = ""; }; 34 | 56722E0F1FC2D1A0000198CB /* main.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = main.m; sourceTree = ""; }; 35 | 5682AEDB1FC563E3001B31AD /* NSString+ZGExtension.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = "NSString+ZGExtension.m"; sourceTree = ""; }; 36 | 5682AEDC1FC563E3001B31AD /* ZGWKWebViewCache.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ZGWKWebViewCache.m; sourceTree = ""; }; 37 | 5682AEDD1FC563E3001B31AD /* ZGWKWebViewCache.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ZGWKWebViewCache.h; sourceTree = ""; }; 38 | 5682AEDE1FC563E3001B31AD /* FileUtil.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = FileUtil.h; sourceTree = ""; }; 39 | 5682AEDF1FC563E3001B31AD /* ZGCacheModel.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ZGCacheModel.h; sourceTree = ""; }; 40 | 5682AEE01FC563E3001B31AD /* FileUtil.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = FileUtil.m; sourceTree = ""; }; 41 | 5682AEE11FC563E3001B31AD /* ZGCacheModel.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ZGCacheModel.m; sourceTree = ""; }; 42 | 5682AEE21FC563E3001B31AD /* ZGURLProtocol.m */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.objc; path = ZGURLProtocol.m; sourceTree = ""; }; 43 | 5682AEE31FC563E3001B31AD /* ZGURLProtocol.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = ZGURLProtocol.h; sourceTree = ""; }; 44 | 5682AEE41FC563E3001B31AD /* NSString+ZGExtension.h */ = {isa = PBXFileReference; fileEncoding = 4; lastKnownFileType = sourcecode.c.h; path = "NSString+ZGExtension.h"; sourceTree = ""; }; 45 | 5682AEED1FC56583001B31AD /* NSURLProtocol+WKWebView.h */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.h; path = "NSURLProtocol+WKWebView.h"; sourceTree = ""; }; 46 | 5682AEEE1FC56583001B31AD /* NSURLProtocol+WKWebView.m */ = {isa = PBXFileReference; lastKnownFileType = sourcecode.c.objc; path = "NSURLProtocol+WKWebView.m"; sourceTree = ""; }; 47 | /* End PBXFileReference section */ 48 | 49 | /* Begin PBXFrameworksBuildPhase section */ 50 | 56722DFA1FC2D1A0000198CB /* Frameworks */ = { 51 | isa = PBXFrameworksBuildPhase; 52 | buildActionMask = 2147483647; 53 | files = ( 54 | ); 55 | runOnlyForDeploymentPostprocessing = 0; 56 | }; 57 | /* End PBXFrameworksBuildPhase section */ 58 | 59 | /* Begin PBXGroup section */ 60 | 56722DF41FC2D19F000198CB = { 61 | isa = PBXGroup; 62 | children = ( 63 | 56722DFF1FC2D1A0000198CB /* ZGWKWebViewCache */, 64 | 56722DFE1FC2D1A0000198CB /* Products */, 65 | ); 66 | sourceTree = ""; 67 | }; 68 | 56722DFE1FC2D1A0000198CB /* Products */ = { 69 | isa = PBXGroup; 70 | children = ( 71 | 56722DFD1FC2D1A0000198CB /* ZGWKWebViewCache.app */, 72 | ); 73 | name = Products; 74 | sourceTree = ""; 75 | }; 76 | 56722DFF1FC2D1A0000198CB /* ZGWKWebViewCache */ = { 77 | isa = PBXGroup; 78 | children = ( 79 | 56722E161FC2D1F2000198CB /* ZGWKWebViewCache */, 80 | 56722E001FC2D1A0000198CB /* AppDelegate.h */, 81 | 56722E011FC2D1A0000198CB /* AppDelegate.m */, 82 | 56722E031FC2D1A0000198CB /* ViewController.h */, 83 | 56722E041FC2D1A0000198CB /* ViewController.m */, 84 | 56722E061FC2D1A0000198CB /* Main.storyboard */, 85 | 56722E091FC2D1A0000198CB /* Assets.xcassets */, 86 | 56722E0B1FC2D1A0000198CB /* LaunchScreen.storyboard */, 87 | 56722E0E1FC2D1A0000198CB /* Info.plist */, 88 | 56722E0F1FC2D1A0000198CB /* main.m */, 89 | ); 90 | path = ZGWKWebViewCache; 91 | sourceTree = ""; 92 | }; 93 | 56722E161FC2D1F2000198CB /* ZGWKWebViewCache */ = { 94 | isa = PBXGroup; 95 | children = ( 96 | 5682AEED1FC56583001B31AD /* NSURLProtocol+WKWebView.h */, 97 | 5682AEEE1FC56583001B31AD /* NSURLProtocol+WKWebView.m */, 98 | 5682AEDE1FC563E3001B31AD /* FileUtil.h */, 99 | 5682AEE01FC563E3001B31AD /* FileUtil.m */, 100 | 5682AEE41FC563E3001B31AD /* NSString+ZGExtension.h */, 101 | 5682AEDB1FC563E3001B31AD /* NSString+ZGExtension.m */, 102 | 5682AEDF1FC563E3001B31AD /* ZGCacheModel.h */, 103 | 5682AEE11FC563E3001B31AD /* ZGCacheModel.m */, 104 | 5682AEDD1FC563E3001B31AD /* ZGWKWebViewCache.h */, 105 | 5682AEDC1FC563E3001B31AD /* ZGWKWebViewCache.m */, 106 | 5682AEE31FC563E3001B31AD /* ZGURLProtocol.h */, 107 | 5682AEE21FC563E3001B31AD /* ZGURLProtocol.m */, 108 | ); 109 | path = ZGWKWebViewCache; 110 | sourceTree = ""; 111 | }; 112 | /* End PBXGroup section */ 113 | 114 | /* Begin PBXNativeTarget section */ 115 | 56722DFC1FC2D1A0000198CB /* ZGWKWebViewCache */ = { 116 | isa = PBXNativeTarget; 117 | buildConfigurationList = 56722E131FC2D1A0000198CB /* Build configuration list for PBXNativeTarget "ZGWKWebViewCache" */; 118 | buildPhases = ( 119 | 56722DF91FC2D1A0000198CB /* Sources */, 120 | 56722DFA1FC2D1A0000198CB /* Frameworks */, 121 | 56722DFB1FC2D1A0000198CB /* Resources */, 122 | ); 123 | buildRules = ( 124 | ); 125 | dependencies = ( 126 | ); 127 | name = ZGWKWebViewCache; 128 | productName = ZGWKWebViewCache; 129 | productReference = 56722DFD1FC2D1A0000198CB /* ZGWKWebViewCache.app */; 130 | productType = "com.apple.product-type.application"; 131 | }; 132 | /* End PBXNativeTarget section */ 133 | 134 | /* Begin PBXProject section */ 135 | 56722DF51FC2D19F000198CB /* Project object */ = { 136 | isa = PBXProject; 137 | attributes = { 138 | LastUpgradeCheck = 0910; 139 | ORGANIZATIONNAME = zhanggui; 140 | TargetAttributes = { 141 | 56722DFC1FC2D1A0000198CB = { 142 | CreatedOnToolsVersion = 9.1; 143 | ProvisioningStyle = Automatic; 144 | }; 145 | }; 146 | }; 147 | buildConfigurationList = 56722DF81FC2D19F000198CB /* Build configuration list for PBXProject "ZGWKWebViewCache" */; 148 | compatibilityVersion = "Xcode 8.0"; 149 | developmentRegion = en; 150 | hasScannedForEncodings = 0; 151 | knownRegions = ( 152 | en, 153 | Base, 154 | ); 155 | mainGroup = 56722DF41FC2D19F000198CB; 156 | productRefGroup = 56722DFE1FC2D1A0000198CB /* Products */; 157 | projectDirPath = ""; 158 | projectRoot = ""; 159 | targets = ( 160 | 56722DFC1FC2D1A0000198CB /* ZGWKWebViewCache */, 161 | ); 162 | }; 163 | /* End PBXProject section */ 164 | 165 | /* Begin PBXResourcesBuildPhase section */ 166 | 56722DFB1FC2D1A0000198CB /* Resources */ = { 167 | isa = PBXResourcesBuildPhase; 168 | buildActionMask = 2147483647; 169 | files = ( 170 | 56722E0D1FC2D1A0000198CB /* LaunchScreen.storyboard in Resources */, 171 | 56722E0A1FC2D1A0000198CB /* Assets.xcassets in Resources */, 172 | 56722E081FC2D1A0000198CB /* Main.storyboard in Resources */, 173 | ); 174 | runOnlyForDeploymentPostprocessing = 0; 175 | }; 176 | /* End PBXResourcesBuildPhase section */ 177 | 178 | /* Begin PBXSourcesBuildPhase section */ 179 | 56722DF91FC2D1A0000198CB /* Sources */ = { 180 | isa = PBXSourcesBuildPhase; 181 | buildActionMask = 2147483647; 182 | files = ( 183 | 5682AEE91FC563E4001B31AD /* ZGURLProtocol.m in Sources */, 184 | 56722E051FC2D1A0000198CB /* ViewController.m in Sources */, 185 | 5682AEE61FC563E4001B31AD /* ZGWKWebViewCache.m in Sources */, 186 | 56722E101FC2D1A0000198CB /* main.m in Sources */, 187 | 5682AEE81FC563E4001B31AD /* ZGCacheModel.m in Sources */, 188 | 5682AEE71FC563E4001B31AD /* FileUtil.m in Sources */, 189 | 5682AEE51FC563E4001B31AD /* NSString+ZGExtension.m in Sources */, 190 | 5682AEEF1FC56583001B31AD /* NSURLProtocol+WKWebView.m in Sources */, 191 | 56722E021FC2D1A0000198CB /* AppDelegate.m in Sources */, 192 | ); 193 | runOnlyForDeploymentPostprocessing = 0; 194 | }; 195 | /* End PBXSourcesBuildPhase section */ 196 | 197 | /* Begin PBXVariantGroup section */ 198 | 56722E061FC2D1A0000198CB /* Main.storyboard */ = { 199 | isa = PBXVariantGroup; 200 | children = ( 201 | 56722E071FC2D1A0000198CB /* Base */, 202 | ); 203 | name = Main.storyboard; 204 | sourceTree = ""; 205 | }; 206 | 56722E0B1FC2D1A0000198CB /* LaunchScreen.storyboard */ = { 207 | isa = PBXVariantGroup; 208 | children = ( 209 | 56722E0C1FC2D1A0000198CB /* Base */, 210 | ); 211 | name = LaunchScreen.storyboard; 212 | sourceTree = ""; 213 | }; 214 | /* End PBXVariantGroup section */ 215 | 216 | /* Begin XCBuildConfiguration section */ 217 | 56722E111FC2D1A0000198CB /* Debug */ = { 218 | isa = XCBuildConfiguration; 219 | buildSettings = { 220 | ALWAYS_SEARCH_USER_PATHS = NO; 221 | CLANG_ANALYZER_NONNULL = YES; 222 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; 223 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; 224 | CLANG_CXX_LIBRARY = "libc++"; 225 | CLANG_ENABLE_MODULES = YES; 226 | CLANG_ENABLE_OBJC_ARC = YES; 227 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 228 | CLANG_WARN_BOOL_CONVERSION = YES; 229 | CLANG_WARN_COMMA = YES; 230 | CLANG_WARN_CONSTANT_CONVERSION = YES; 231 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 232 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 233 | CLANG_WARN_EMPTY_BODY = YES; 234 | CLANG_WARN_ENUM_CONVERSION = YES; 235 | CLANG_WARN_INFINITE_RECURSION = YES; 236 | CLANG_WARN_INT_CONVERSION = YES; 237 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 238 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 239 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 240 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 241 | CLANG_WARN_STRICT_PROTOTYPES = YES; 242 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 243 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; 244 | CLANG_WARN_UNREACHABLE_CODE = YES; 245 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 246 | CODE_SIGN_IDENTITY = "iPhone Developer"; 247 | COPY_PHASE_STRIP = NO; 248 | DEBUG_INFORMATION_FORMAT = dwarf; 249 | ENABLE_STRICT_OBJC_MSGSEND = YES; 250 | ENABLE_TESTABILITY = YES; 251 | GCC_C_LANGUAGE_STANDARD = gnu11; 252 | GCC_DYNAMIC_NO_PIC = NO; 253 | GCC_NO_COMMON_BLOCKS = YES; 254 | GCC_OPTIMIZATION_LEVEL = 0; 255 | GCC_PREPROCESSOR_DEFINITIONS = ( 256 | "DEBUG=1", 257 | "$(inherited)", 258 | ); 259 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 260 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 261 | GCC_WARN_UNDECLARED_SELECTOR = YES; 262 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 263 | GCC_WARN_UNUSED_FUNCTION = YES; 264 | GCC_WARN_UNUSED_VARIABLE = YES; 265 | IPHONEOS_DEPLOYMENT_TARGET = 11.1; 266 | MTL_ENABLE_DEBUG_INFO = YES; 267 | ONLY_ACTIVE_ARCH = YES; 268 | SDKROOT = iphoneos; 269 | }; 270 | name = Debug; 271 | }; 272 | 56722E121FC2D1A0000198CB /* Release */ = { 273 | isa = XCBuildConfiguration; 274 | buildSettings = { 275 | ALWAYS_SEARCH_USER_PATHS = NO; 276 | CLANG_ANALYZER_NONNULL = YES; 277 | CLANG_ANALYZER_NUMBER_OBJECT_CONVERSION = YES_AGGRESSIVE; 278 | CLANG_CXX_LANGUAGE_STANDARD = "gnu++14"; 279 | CLANG_CXX_LIBRARY = "libc++"; 280 | CLANG_ENABLE_MODULES = YES; 281 | CLANG_ENABLE_OBJC_ARC = YES; 282 | CLANG_WARN_BLOCK_CAPTURE_AUTORELEASING = YES; 283 | CLANG_WARN_BOOL_CONVERSION = YES; 284 | CLANG_WARN_COMMA = YES; 285 | CLANG_WARN_CONSTANT_CONVERSION = YES; 286 | CLANG_WARN_DIRECT_OBJC_ISA_USAGE = YES_ERROR; 287 | CLANG_WARN_DOCUMENTATION_COMMENTS = YES; 288 | CLANG_WARN_EMPTY_BODY = YES; 289 | CLANG_WARN_ENUM_CONVERSION = YES; 290 | CLANG_WARN_INFINITE_RECURSION = YES; 291 | CLANG_WARN_INT_CONVERSION = YES; 292 | CLANG_WARN_NON_LITERAL_NULL_CONVERSION = YES; 293 | CLANG_WARN_OBJC_LITERAL_CONVERSION = YES; 294 | CLANG_WARN_OBJC_ROOT_CLASS = YES_ERROR; 295 | CLANG_WARN_RANGE_LOOP_ANALYSIS = YES; 296 | CLANG_WARN_STRICT_PROTOTYPES = YES; 297 | CLANG_WARN_SUSPICIOUS_MOVE = YES; 298 | CLANG_WARN_UNGUARDED_AVAILABILITY = YES_AGGRESSIVE; 299 | CLANG_WARN_UNREACHABLE_CODE = YES; 300 | CLANG_WARN__DUPLICATE_METHOD_MATCH = YES; 301 | CODE_SIGN_IDENTITY = "iPhone Developer"; 302 | COPY_PHASE_STRIP = NO; 303 | DEBUG_INFORMATION_FORMAT = "dwarf-with-dsym"; 304 | ENABLE_NS_ASSERTIONS = NO; 305 | ENABLE_STRICT_OBJC_MSGSEND = YES; 306 | GCC_C_LANGUAGE_STANDARD = gnu11; 307 | GCC_NO_COMMON_BLOCKS = YES; 308 | GCC_WARN_64_TO_32_BIT_CONVERSION = YES; 309 | GCC_WARN_ABOUT_RETURN_TYPE = YES_ERROR; 310 | GCC_WARN_UNDECLARED_SELECTOR = YES; 311 | GCC_WARN_UNINITIALIZED_AUTOS = YES_AGGRESSIVE; 312 | GCC_WARN_UNUSED_FUNCTION = YES; 313 | GCC_WARN_UNUSED_VARIABLE = YES; 314 | IPHONEOS_DEPLOYMENT_TARGET = 11.1; 315 | MTL_ENABLE_DEBUG_INFO = NO; 316 | SDKROOT = iphoneos; 317 | VALIDATE_PRODUCT = YES; 318 | }; 319 | name = Release; 320 | }; 321 | 56722E141FC2D1A0000198CB /* Debug */ = { 322 | isa = XCBuildConfiguration; 323 | buildSettings = { 324 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 325 | CODE_SIGN_STYLE = Automatic; 326 | DEVELOPMENT_TEAM = 4ATZY28W58; 327 | INFOPLIST_FILE = ZGWKWebViewCache/Info.plist; 328 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 329 | PRODUCT_BUNDLE_IDENTIFIER = com.shuqu.ZGWKWebViewCache; 330 | PRODUCT_NAME = "$(TARGET_NAME)"; 331 | TARGETED_DEVICE_FAMILY = "1,2"; 332 | }; 333 | name = Debug; 334 | }; 335 | 56722E151FC2D1A0000198CB /* Release */ = { 336 | isa = XCBuildConfiguration; 337 | buildSettings = { 338 | ASSETCATALOG_COMPILER_APPICON_NAME = AppIcon; 339 | CODE_SIGN_STYLE = Automatic; 340 | DEVELOPMENT_TEAM = 4ATZY28W58; 341 | INFOPLIST_FILE = ZGWKWebViewCache/Info.plist; 342 | LD_RUNPATH_SEARCH_PATHS = "$(inherited) @executable_path/Frameworks"; 343 | PRODUCT_BUNDLE_IDENTIFIER = com.shuqu.ZGWKWebViewCache; 344 | PRODUCT_NAME = "$(TARGET_NAME)"; 345 | TARGETED_DEVICE_FAMILY = "1,2"; 346 | }; 347 | name = Release; 348 | }; 349 | /* End XCBuildConfiguration section */ 350 | 351 | /* Begin XCConfigurationList section */ 352 | 56722DF81FC2D19F000198CB /* Build configuration list for PBXProject "ZGWKWebViewCache" */ = { 353 | isa = XCConfigurationList; 354 | buildConfigurations = ( 355 | 56722E111FC2D1A0000198CB /* Debug */, 356 | 56722E121FC2D1A0000198CB /* Release */, 357 | ); 358 | defaultConfigurationIsVisible = 0; 359 | defaultConfigurationName = Release; 360 | }; 361 | 56722E131FC2D1A0000198CB /* Build configuration list for PBXNativeTarget "ZGWKWebViewCache" */ = { 362 | isa = XCConfigurationList; 363 | buildConfigurations = ( 364 | 56722E141FC2D1A0000198CB /* Debug */, 365 | 56722E151FC2D1A0000198CB /* Release */, 366 | ); 367 | defaultConfigurationIsVisible = 0; 368 | defaultConfigurationName = Release; 369 | }; 370 | /* End XCConfigurationList section */ 371 | }; 372 | rootObject = 56722DF51FC2D19F000198CB /* Project object */; 373 | } 374 | -------------------------------------------------------------------------------- /ZGWKWebViewCache.xcodeproj/project.xcworkspace/contents.xcworkspacedata: -------------------------------------------------------------------------------- 1 | 2 | 4 | 6 | 7 | 8 | -------------------------------------------------------------------------------- /ZGWKWebViewCache.xcodeproj/project.xcworkspace/xcuserdata/zhanggui.xcuserdatad/UserInterfaceState.xcuserstate: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/ScottZg/ZGWKWebViewCache/7593d8e30cacea0e2f0a215983e54346ff80ee54/ZGWKWebViewCache.xcodeproj/project.xcworkspace/xcuserdata/zhanggui.xcuserdatad/UserInterfaceState.xcuserstate -------------------------------------------------------------------------------- /ZGWKWebViewCache.xcodeproj/xcuserdata/zhanggui.xcuserdatad/xcdebugger/Breakpoints_v2.xcbkptlist: -------------------------------------------------------------------------------- 1 | 2 | 5 | 6 | 8 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /ZGWKWebViewCache.xcodeproj/xcuserdata/zhanggui.xcuserdatad/xcschemes/xcschememanagement.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | SchemeUserState 6 | 7 | ZGWKWebViewCache.xcscheme 8 | 9 | orderHint 10 | 0 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/AppDelegate.h: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.h 3 | // ZGWKWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface AppDelegate : UIResponder 12 | 13 | @property (strong, nonatomic) UIWindow *window; 14 | 15 | 16 | @end 17 | 18 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/AppDelegate.m: -------------------------------------------------------------------------------- 1 | // 2 | // AppDelegate.m 3 | // ZGWKWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "AppDelegate.h" 10 | #import "ZGWKWebViewCache.h" 11 | @interface AppDelegate () 12 | 13 | @end 14 | 15 | @implementation AppDelegate 16 | 17 | 18 | - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { 19 | [[ZGWKWebViewCache sharedWebViewCache] initWebCacheWithCacheTypes:@[@(CacheTypeJS),@(CacheTypeImage)]]; 20 | [[ZGWKWebViewCache sharedWebViewCache] setDebugModel:YES]; 21 | [[ZGWKWebViewCache sharedWebViewCache] clearCacheWithInvalidDays:7]; 22 | 23 | return YES; 24 | } 25 | 26 | @end 27 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/Assets.xcassets/AppIcon.appiconset/Contents.json: -------------------------------------------------------------------------------- 1 | { 2 | "images" : [ 3 | { 4 | "idiom" : "iphone", 5 | "size" : "20x20", 6 | "scale" : "2x" 7 | }, 8 | { 9 | "idiom" : "iphone", 10 | "size" : "20x20", 11 | "scale" : "3x" 12 | }, 13 | { 14 | "idiom" : "iphone", 15 | "size" : "29x29", 16 | "scale" : "2x" 17 | }, 18 | { 19 | "idiom" : "iphone", 20 | "size" : "29x29", 21 | "scale" : "3x" 22 | }, 23 | { 24 | "idiom" : "iphone", 25 | "size" : "40x40", 26 | "scale" : "2x" 27 | }, 28 | { 29 | "idiom" : "iphone", 30 | "size" : "40x40", 31 | "scale" : "3x" 32 | }, 33 | { 34 | "idiom" : "iphone", 35 | "size" : "60x60", 36 | "scale" : "2x" 37 | }, 38 | { 39 | "idiom" : "iphone", 40 | "size" : "60x60", 41 | "scale" : "3x" 42 | }, 43 | { 44 | "idiom" : "ipad", 45 | "size" : "20x20", 46 | "scale" : "1x" 47 | }, 48 | { 49 | "idiom" : "ipad", 50 | "size" : "20x20", 51 | "scale" : "2x" 52 | }, 53 | { 54 | "idiom" : "ipad", 55 | "size" : "29x29", 56 | "scale" : "1x" 57 | }, 58 | { 59 | "idiom" : "ipad", 60 | "size" : "29x29", 61 | "scale" : "2x" 62 | }, 63 | { 64 | "idiom" : "ipad", 65 | "size" : "40x40", 66 | "scale" : "1x" 67 | }, 68 | { 69 | "idiom" : "ipad", 70 | "size" : "40x40", 71 | "scale" : "2x" 72 | }, 73 | { 74 | "idiom" : "ipad", 75 | "size" : "76x76", 76 | "scale" : "1x" 77 | }, 78 | { 79 | "idiom" : "ipad", 80 | "size" : "76x76", 81 | "scale" : "2x" 82 | }, 83 | { 84 | "idiom" : "ipad", 85 | "size" : "83.5x83.5", 86 | "scale" : "2x" 87 | } 88 | ], 89 | "info" : { 90 | "version" : 1, 91 | "author" : "xcode" 92 | } 93 | } -------------------------------------------------------------------------------- /ZGWKWebViewCache/Base.lproj/LaunchScreen.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/Base.lproj/Main.storyboard: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | 48 | 49 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/Info.plist: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | NSAppTransportSecurity 6 | 7 | NSAllowsArbitraryLoads 8 | 9 | 10 | CFBundleDevelopmentRegion 11 | $(DEVELOPMENT_LANGUAGE) 12 | CFBundleExecutable 13 | $(EXECUTABLE_NAME) 14 | CFBundleIdentifier 15 | $(PRODUCT_BUNDLE_IDENTIFIER) 16 | CFBundleInfoDictionaryVersion 17 | 6.0 18 | CFBundleName 19 | $(PRODUCT_NAME) 20 | CFBundlePackageType 21 | APPL 22 | CFBundleShortVersionString 23 | 1.0 24 | CFBundleVersion 25 | 1 26 | LSRequiresIPhoneOS 27 | 28 | UILaunchStoryboardName 29 | LaunchScreen 30 | UIMainStoryboardFile 31 | Main 32 | UIRequiredDeviceCapabilities 33 | 34 | armv7 35 | 36 | UISupportedInterfaceOrientations 37 | 38 | UIInterfaceOrientationPortrait 39 | UIInterfaceOrientationLandscapeLeft 40 | UIInterfaceOrientationLandscapeRight 41 | 42 | UISupportedInterfaceOrientations~ipad 43 | 44 | UIInterfaceOrientationPortrait 45 | UIInterfaceOrientationPortraitUpsideDown 46 | UIInterfaceOrientationLandscapeLeft 47 | UIInterfaceOrientationLandscapeRight 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ViewController.h: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.h 3 | // ZGWKWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ViewController : UIViewController 12 | 13 | 14 | @end 15 | 16 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ViewController.m: -------------------------------------------------------------------------------- 1 | // 2 | // ViewController.m 3 | // ZGWKWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "ViewController.h" 10 | #import 11 | #import "ZGWKWebViewCache.h" 12 | @interface ViewController () 13 | @property (strong, nonatomic) WKWebView *myWKWebView; 14 | 15 | @end 16 | 17 | @implementation ViewController 18 | 19 | - (void)viewDidLoad { 20 | [super viewDidLoad]; 21 | [ZGWKWebViewCache registerSchemeCache]; //在需要缓存的页面注册scheme 22 | NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://172.16.10.35:3333/src/p/about/index.html"]]; 23 | [self.myWKWebView loadRequest:request]; 24 | } 25 | 26 | 27 | - (WKWebView *)myWKWebView { 28 | if (!_myWKWebView) { 29 | _myWKWebView = [[WKWebView alloc] initWithFrame:self.view.frame]; 30 | [self.view addSubview:_myWKWebView]; 31 | } 32 | return _myWKWebView; 33 | } 34 | 35 | 36 | @end 37 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ZGWKWebViewCache/FileUtil.h: -------------------------------------------------------------------------------- 1 | // 2 | // FileUtil.h 3 | // RongShu 4 | // 5 | // Created by zhanggui on 2017/11/9. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface FileUtil : NSObject 12 | 13 | 14 | @property (nonatomic,assign)BOOL debug; 15 | 16 | - (instancetype)init NS_UNAVAILABLE; 17 | 18 | + (instancetype)shared; 19 | 20 | 21 | - (void)write:(NSData *)data forKey:(NSString *)key; 22 | 23 | 24 | 25 | -(NSData *)readForKey:(NSString *)key; 26 | 27 | 28 | 29 | - (void)clearCacheFolder; 30 | @end 31 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ZGWKWebViewCache/FileUtil.m: -------------------------------------------------------------------------------- 1 | // 2 | // FileUtil.m 3 | // RongShu 4 | // 5 | // Created by zhanggui on 2017/11/9. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "FileUtil.h" 10 | 11 | #import "NSString+ZGExtension.h" 12 | static inline NSString * RSFileCacheDirectory() { 13 | static NSString * _fileDic; 14 | static dispatch_once_t onceToken; 15 | dispatch_once(&onceToken, ^{ 16 | _fileDic = NSSearchPathForDirectoriesInDomains( NSCachesDirectory, NSUserDomainMask, YES )[0]; 17 | }); 18 | return _fileDic; 19 | } 20 | 21 | static inline NSString *cachePathForKey(NSString *key) { 22 | NSString *fileName = [NSString SHA1FromString:key]; 23 | NSString *filePath = [RSFileCacheDirectory() stringByAppendingString:@"/ZGWebCaches"]; 24 | if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) { 25 | [[NSFileManager defaultManager] createDirectoryAtPath:filePath withIntermediateDirectories:YES attributes:nil error:nil]; 26 | } 27 | return [[filePath stringByAppendingString:@"/"] stringByAppendingString:fileName]; 28 | } 29 | @interface FileUtil () 30 | 31 | @property (nonatomic,strong)NSCache *cache; 32 | 33 | 34 | 35 | @property (nonatomic,strong)dispatch_queue_t zgQueue; 36 | @end 37 | 38 | 39 | 40 | @implementation FileUtil 41 | 42 | 43 | + (instancetype)shared { 44 | static FileUtil *util = nil; 45 | static dispatch_once_t onceToken; 46 | dispatch_once(&onceToken, ^{ 47 | util = [[self alloc] init]; 48 | }); 49 | return util; 50 | } 51 | - (id)init { 52 | self = [super init]; 53 | if (self) { 54 | _debug = true; 55 | } 56 | return self; 57 | } 58 | - (void)clearCacheFolder { 59 | NSString *cacheFolder = [RSFileCacheDirectory() stringByAppendingString:@"/RSWebCaches"]; 60 | NSError *error; 61 | NSArray *contents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:cacheFolder error:&error]; 62 | if (error || !contents || contents.count<=0) { 63 | return; 64 | } 65 | for (NSString *fileName in contents) { 66 | NSString *path = [NSString stringWithFormat:@"/%@",fileName]; 67 | NSString *filePath = [cacheFolder stringByAppendingString:path]; 68 | BOOL bo = [[NSFileManager defaultManager] removeItemAtPath:filePath error:&error]; 69 | if (bo) { 70 | NSString *str = [NSString stringWithFormat:@"移除%@成功",filePath]; 71 | [self ZGLog:str]; 72 | } 73 | } 74 | 75 | } 76 | //内存 -> 文件系统 77 | - (NSData *)readForKey:(NSString *)key { 78 | if (!key) { 79 | return nil; 80 | } 81 | NSData *cacheData = [self.cache objectForKey:key]; 82 | if (cacheData) { 83 | NSString *str = [NSString stringWithFormat:@"从cache中读取%@",key]; 84 | [self ZGLog:str]; 85 | return cacheData; 86 | }else { 87 | NSString *str = [NSString stringWithFormat:@"从cache无法读取,从文件读取从cache中读取%@",key]; 88 | [self ZGLog:str]; 89 | NSString *filePath = cachePathForKey(key); 90 | NSData *fileData = [[NSFileManager defaultManager] contentsAtPath:filePath]; 91 | if (fileData) { 92 | [self.cache setObject:fileData forKey:key]; 93 | } 94 | return fileData; 95 | } 96 | return nil; 97 | } 98 | - (void)write:(NSData *)data forKey:(NSString *)key { 99 | NSString *filePath = cachePathForKey(key); 100 | NSURL *fileUrl = [NSURL fileURLWithPath:filePath]; 101 | [self.cache setObject:data forKey:key]; 102 | dispatch_async(self.zgQueue, ^{ 103 | BOOL boo = [[NSFileManager defaultManager] createFileAtPath:fileUrl.path contents:data attributes:nil]; 104 | if (boo) { 105 | NSString *str = [NSString stringWithFormat:@"创建%@成功",filePath]; 106 | [self ZGLog:str]; 107 | 108 | }else { 109 | NSString *str = [NSString stringWithFormat:@"创建%@失败",filePath]; 110 | [self ZGLog:str]; 111 | } 112 | }); 113 | } 114 | - (void)ZGLog:(NSString *)str { 115 | if (_debug) { 116 | NSLog(@"%@", str); 117 | } 118 | } 119 | - (dispatch_queue_t)zgQueue { 120 | if (!_zgQueue) { 121 | _zgQueue = dispatch_queue_create("com.zgCache.zgCache", DISPATCH_QUEUE_CONCURRENT); 122 | } 123 | return _zgQueue; 124 | } 125 | - (NSCache *)cache { 126 | if (!_cache) { 127 | _cache = [[NSCache alloc] init]; 128 | } 129 | return _cache; 130 | } 131 | @end 132 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ZGWKWebViewCache/NSString+ZGExtension.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSString+Extension.h 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface NSString (ZGExtension) 12 | 13 | /** 14 | SHA1 15 | 16 | @param string 要sha1的string 17 | @return 返回sha1后的str 18 | */ 19 | + (NSString *)SHA1FromString:(NSString *)string; 20 | @end 21 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ZGWKWebViewCache/NSString+ZGExtension.m: -------------------------------------------------------------------------------- 1 | // 2 | // NSString+Extension.m 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "NSString+ZGExtension.h" 10 | #import 11 | @implementation NSString (ZGExtension) 12 | 13 | #pragma mark - Hash methods 14 | + (NSString *)SHA1FromString:(NSString *)string { 15 | unsigned char digest[CC_SHA1_DIGEST_LENGTH]; 16 | 17 | NSData *stringBytes = [string dataUsingEncoding:NSUTF8StringEncoding]; 18 | 19 | if (CC_SHA1([stringBytes bytes], (CC_LONG)[stringBytes length], digest)) { 20 | 21 | NSMutableString *output = [NSMutableString stringWithCapacity:CC_SHA1_DIGEST_LENGTH * 2]; 22 | 23 | for (int i = 0; i < CC_SHA1_DIGEST_LENGTH; i++) { 24 | [output appendFormat:@"%02x", digest[i]]; 25 | } 26 | 27 | return output; 28 | } 29 | return nil; 30 | } 31 | @end 32 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ZGWKWebViewCache/NSURLProtocol+WKWebView.h: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLProtocol+WKWebView.h 3 | // ZGWKWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/22. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface NSURLProtocol (WKWebView) 12 | 13 | 14 | + (void)zg_registerScheme:(NSString *)scheme; 15 | 16 | 17 | + (void)zg_unregisterScheme:(NSString *)scheme; 18 | @end 19 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ZGWKWebViewCache/NSURLProtocol+WKWebView.m: -------------------------------------------------------------------------------- 1 | // 2 | // NSURLProtocol+WKWebView.m 3 | // ZGWKWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/22. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "NSURLProtocol+WKWebView.h" 10 | #import 11 | 12 | 13 | FOUNDATION_STATIC_INLINE Class ContextControllerClass() { 14 | static Class cls; 15 | if (!cls) { 16 | cls = [[[WKWebView new] valueForKey:@"browsingContextController"] class]; 17 | } 18 | return cls; 19 | } 20 | FOUNDATION_STATIC_INLINE SEL RegisterSchemeSelector () { 21 | return NSSelectorFromString(@"registerSchemeForCustomProtocol:"); 22 | } 23 | FOUNDATION_STATIC_INLINE SEL UnregisterSchemeSelector () { 24 | return NSSelectorFromString(@"unregisterSchemeForCustomProtocol:"); 25 | } 26 | 27 | @implementation NSURLProtocol (WKWebView) 28 | 29 | + (void)zg_registerScheme:(NSString *)scheme { 30 | Class cls = ContextControllerClass(); 31 | SEL sel = RegisterSchemeSelector(); 32 | if ([(id)cls respondsToSelector:sel]) { 33 | #pragma clang diagnostic push 34 | #pragma clang diagnostic ignored "-Warc-performSelector-leaks" 35 | [(id)cls performSelector:sel withObject:scheme]; 36 | #pragma clang diagnostic pop 37 | } 38 | } 39 | + (void)zg_unregisterScheme:(NSString *)scheme { 40 | Class cls = ContextControllerClass(); 41 | SEL sel = UnregisterSchemeSelector(); 42 | if ([(id)cls respondsToSelector:sel]) { 43 | #pragma clang diagnostic push 44 | #pragma clang diagnostic ignored "-Warc-performSelector-leaks" 45 | [(id)cls performSelector:sel withObject:scheme]; 46 | #pragma clang diagnostic pop 47 | } 48 | } 49 | @end 50 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ZGWKWebViewCache/ZGCacheModel.h: -------------------------------------------------------------------------------- 1 | // 2 | // ZGCacheModel.h 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ZGCacheModel : NSObject 12 | 13 | /** 14 | mime 类型 15 | */ 16 | @property (nonatomic,strong)NSString *MIMEType; 17 | 18 | 19 | /** 20 | 缓存数据 21 | */ 22 | @property (nonatomic,strong)NSData *data; 23 | @end 24 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ZGWKWebViewCache/ZGCacheModel.m: -------------------------------------------------------------------------------- 1 | // 2 | // ZGCacheModel.m 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "ZGCacheModel.h" 10 | 11 | @implementation ZGCacheModel 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ZGWKWebViewCache/ZGURLProtocol.h: -------------------------------------------------------------------------------- 1 | // 2 | // ZGURLProtocol.h 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | 11 | @interface ZGURLProtocol : NSURLProtocol 12 | 13 | @end 14 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ZGWKWebViewCache/ZGURLProtocol.m: -------------------------------------------------------------------------------- 1 | // 2 | // ZGURLProtocol.m 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "ZGURLProtocol.h" 10 | #import "ZGCacheModel.h" 11 | #import "ZGWKWebViewCache.h" 12 | static NSString * const ZGURLProtocolKey = @"zgPKey"; 13 | 14 | @interface ZGURLProtocol() 15 | 16 | /** 17 | 请求的数据 18 | */ 19 | @property (nonatomic,strong)NSMutableData *responseData; 20 | 21 | /** 22 | task 23 | */ 24 | @property (nonatomic,strong)NSURLSessionDataTask *task; 25 | 26 | @end 27 | 28 | @implementation ZGURLProtocol 29 | 30 | + (BOOL)canInitWithRequest:(NSURLRequest *)request { 31 | NSString *scheme = [[request URL] scheme]; 32 | if ([scheme caseInsensitiveCompare:@"http"] == NSOrderedSame || [scheme caseInsensitiveCompare:@"https"] == NSOrderedSame) { //只缓存http和https的请求 33 | NSString *str = request.URL.path; 34 | if ([self cacheTypeWithStr:str] && ![NSURLProtocol propertyForKey:ZGURLProtocolKey inRequest:request]) { 35 | return YES; 36 | } 37 | } 38 | return NO; 39 | } 40 | + (BOOL)cacheTypeWithStr:(NSString *)str { 41 | if ([[[ZGWKWebViewCache sharedWebViewCache] cacheArr] containsObject:@(CacheTypeJS)] && [str hasSuffix:@".js"]) { 42 | return YES; 43 | } 44 | if ([[[ZGWKWebViewCache sharedWebViewCache] cacheArr] containsObject:@(CacheTypeImage)] && [self ifImageType:str]) { 45 | return YES; 46 | } 47 | if ([[[ZGWKWebViewCache sharedWebViewCache] cacheArr] containsObject:@(CacheTypeCSS)] && [str hasSuffix:@".css"]) { 48 | return YES; 49 | } 50 | if ([[[ZGWKWebViewCache sharedWebViewCache] cacheArr] containsObject:@(CacheTypeHTML)] && [str hasSuffix:@".html"]) { 51 | return YES; 52 | } 53 | return NO; 54 | } 55 | /** 56 | 判断是否值js 57 | 58 | @param urlStr 资源地址,这里暂时只判断了一下js 59 | @return YES表示是js,NO表示不是js 60 | */ 61 | + (BOOL)ifJSType:(NSString *)urlStr { 62 | if ([urlStr hasSuffix:@".js"]) { 63 | return YES; 64 | } 65 | return NO; 66 | } 67 | /** 68 | 判断将要请求的资源是否是图片 69 | 70 | @param urlStr 资源地址,这里暂时只判断了一下png/jpg/gif/jpeg四种格式 71 | @return YES表示是图片,NO表示不是图片 72 | */ 73 | + (BOOL)ifImageType:(NSString *)urlStr { 74 | if ([urlStr hasSuffix:@".png"] || 75 | [urlStr hasSuffix:@".jpg"] || 76 | [urlStr hasSuffix:@".gif"] || 77 | [urlStr hasSuffix:@".jpeg"]) { 78 | return YES; 79 | } 80 | return NO; 81 | } 82 | + (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request { 83 | //这里可以进行重定向操作,重写request, 84 | return request; 85 | } 86 | //这里请求是否的等价于缓存 87 | + (BOOL)requestIsCacheEquivalent:(NSURLRequest *)a toRequest:(NSURLRequest *)b { 88 | return [super requestIsCacheEquivalent:a toRequest:b]; 89 | } 90 | //开始请求 91 | - (void)startLoading { 92 | NSMutableURLRequest *mutableRequest = [[self request] mutableCopy]; 93 | [NSURLProtocol setProperty:@YES forKey:ZGURLProtocolKey inRequest:mutableRequest]; 94 | ZGCacheModel *model = [[ZGWKWebViewCache sharedWebViewCache] getCacheDataByKey:self.request.URL.absoluteString]; 95 | 96 | if (model.data && model.MIMEType) { 97 | NSURLResponse *response = [[NSURLResponse alloc] initWithURL:self.request.URL MIMEType:model.MIMEType expectedContentLength:model.data.length textEncodingName:nil]; 98 | [self.client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed]; 99 | [self.client URLProtocol:self didLoadData:model.data]; 100 | [self.client URLProtocolDidFinishLoading:self]; 101 | }else { 102 | NSURLSession *session = [NSURLSession sessionWithConfiguration:[NSURLSessionConfiguration defaultSessionConfiguration] delegate:self delegateQueue:nil]; 103 | self.task = [session dataTaskWithRequest:self.request]; 104 | [self.task resume]; 105 | } 106 | } 107 | - (void)stopLoading { 108 | if (self.task) { 109 | [self.task cancel]; 110 | } 111 | } 112 | 113 | #pragma mark - NSURLConnectionDelegate 114 | - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler { 115 | self.responseData = [NSMutableData data]; 116 | [[self client] URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageAllowed]; 117 | 118 | completionHandler(NSURLSessionResponseAllow); 119 | } 120 | - (void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data { 121 | [self.responseData appendData:data]; 122 | 123 | 124 | [[self client] URLProtocol:self didLoadData:data]; 125 | } 126 | - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error { 127 | if (error) { 128 | [self.client URLProtocolDidFinishLoading:self]; 129 | return; 130 | } 131 | ZGCacheModel *model = [ZGCacheModel new]; 132 | model.data = self.responseData; 133 | model.MIMEType = task.response.MIMEType; 134 | 135 | [self setMiType:model.MIMEType withKey:[self.request.URL path]];//userdefault存储MIMEtype 136 | [[ZGWKWebViewCache sharedWebViewCache] setCacheWithKey:self.request.URL.absoluteString value:model]; 137 | [self.client URLProtocolDidFinishLoading:self]; 138 | } 139 | /** 140 | 将类型和key存储到一个字典里面,然后 141 | 142 | @param mimeType mime类型 143 | @param urlKey url的key 144 | */ 145 | - (void)setMiType:(NSString *)mimeType withKey:(NSString *)urlKey { 146 | NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:URLMIMETYPE]; 147 | 148 | if (!dic) { 149 | dic = [NSMutableDictionary dictionary]; 150 | } 151 | NSMutableDictionary *muDic = [[NSMutableDictionary alloc] initWithDictionary:dic]; 152 | [muDic setValue:mimeType forKey:urlKey]; 153 | [[NSUserDefaults standardUserDefaults] setObject:muDic forKey:URLMIMETYPE]; 154 | [[NSUserDefaults standardUserDefaults] synchronize]; 155 | } 156 | @end 157 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ZGWKWebViewCache/ZGWKWebViewCache.h: -------------------------------------------------------------------------------- 1 | // 2 | // ZGUIWebViewCache.h 3 | // ZGUIWebViewCache 4 | //使用过程中只需要关注该类即可,其他类无需关注 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "ZGCacheModel.h" 11 | 12 | extern NSString *const URLMIMETYPE; 13 | 14 | 15 | typedef NS_ENUM(NSInteger,CacheType) { 16 | CacheTypeImage = 4, 17 | CacheTypeJS, 18 | CacheTypeCSS, 19 | CacheTypeHTML 20 | }; 21 | @interface ZGWKWebViewCache : NSObject 22 | 23 | 24 | /** 25 | 初始化web cache该方法可以直接在application:didFinishLaunchingWithOptions中调用 26 | @param arr 缓存类型,CacheType 27 | */ 28 | - (void)initWebCacheWithCacheTypes:(NSArray *)arr; 29 | 30 | 31 | 32 | 33 | 34 | +(instancetype)sharedWebViewCache; 35 | 36 | 37 | - (instancetype)init NS_UNAVAILABLE; 38 | 39 | 40 | 41 | /** 42 | 注册cache 43 | */ 44 | + (void)registerSchemeCache; 45 | 46 | /** 47 | 不注册cache 48 | */ 49 | + (void)unRegisterSchemeCache; 50 | 51 | /** 52 | 得到缓存的数据 53 | 54 | @param cacheKey 缓存key 55 | @return 返回缓存model 56 | */ 57 | - (ZGCacheModel *)getCacheDataByKey:(NSString *)cacheKey; 58 | 59 | /** 60 | 设置离线缓存,根据需求缓存,如果你的js有版本号,那么如有更新,缓存key便会和原有key不一致,达到更新效果。如果相同的链接内容更改则无法实现即时更新。 61 | 62 | @param key 缓存key 63 | @param model 缓存model 64 | */ 65 | - (void)setCacheWithKey:(NSString *)key value:(ZGCacheModel *)model; 66 | 67 | 68 | /** 69 | 清除缓存,自己在合适的地方调用,比如清除缓存按钮点击 70 | */ 71 | - (void)clearZGCache; 72 | 73 | - (NSArray *)cacheArr; 74 | /** 75 | 清除缓存 76 | 77 | @param day 天数,例如7天,7天后会自动清除所有缓存,该方法可以直接在application:didFinishLaunchingWithOptions中调用 78 | */ 79 | - (void)clearCacheWithInvalidDays:(NSInteger)day; 80 | 81 | 82 | /** 83 | 设置debug模式,是否打印日志,默认为NO,上线请设置为NO 84 | 85 | @param boo YES表示开启debug模式,NO表示关闭debugM模式 86 | */ 87 | - (void)setDebugModel:(BOOL)boo; 88 | 89 | @end 90 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/ZGWKWebViewCache/ZGWKWebViewCache.m: -------------------------------------------------------------------------------- 1 | // 2 | // ZGUIWebViewCache.m 3 | // ZGUIWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import "ZGWKWebViewCache.h" 10 | #import "ZGURLProtocol.h" 11 | #import "FileUtil.h" 12 | #import "NSURLProtocol+WKWebView.h" 13 | NSString * const URLMIMETYPE = @"url_mime_type"; 14 | 15 | 16 | static NSString * const CacheLiveTimeKey = @"CacheLiveTimeKey"; 17 | 18 | static NSInteger const CacheLiveDate = 7; //cache默认缓存时间为7天,7天清理一次缓存 19 | 20 | @interface ZGWKWebViewCache() 21 | @property (nonatomic,assign)BOOL debug; 22 | 23 | 24 | @property (nonatomic,strong)NSArray *cacheTypeArr; 25 | @end 26 | 27 | @implementation ZGWKWebViewCache 28 | 29 | + (instancetype)sharedWebViewCache { 30 | static ZGWKWebViewCache *ch = nil; 31 | static dispatch_once_t onceToken; 32 | dispatch_once(&onceToken, ^{ 33 | ch = [[self alloc] init]; 34 | }); 35 | return ch; 36 | } 37 | - (NSArray *)cacheArr { 38 | return _cacheTypeArr; 39 | } 40 | - (void)initWebCacheWithCacheTypes:(NSArray *)arr { 41 | [NSURLProtocol registerClass:[ZGURLProtocol class]]; 42 | _cacheTypeArr =arr; 43 | } 44 | 45 | - (ZGCacheModel *)getCacheDataByKey:(NSString *)cacheKey { 46 | ZGCacheModel *model = [ZGCacheModel new]; 47 | 48 | FileUtil *util = [FileUtil shared]; 49 | 50 | model.data = [util readForKey:cacheKey]; 51 | if (model.data) { 52 | model.MIMEType = [self getMIMETypeFromKey:cacheKey]; 53 | } 54 | return model; 55 | } 56 | - (void)setCacheWithKey:(NSString *)key value:(ZGCacheModel *)model { 57 | FileUtil *util = [FileUtil shared]; 58 | [util write:model.data forKey:key]; 59 | } 60 | - (void)clearZGCache { 61 | 62 | [[FileUtil shared] clearCacheFolder]; //清除缓存的文件 63 | 64 | [[NSUserDefaults standardUserDefaults] removeObjectForKey:URLMIMETYPE]; //清除mime类型s 65 | [[NSUserDefaults standardUserDefaults] removeObjectForKey:CacheLiveTimeKey]; 66 | 67 | } 68 | - (void)clearCacheWithInvalidDays:(NSInteger)day { 69 | NSDate *originTime = [[NSUserDefaults standardUserDefaults] objectForKey:CacheLiveTimeKey]; //存取当前时间 70 | if (!originTime) { 71 | originTime = [self beijingTime]; 72 | [[NSUserDefaults standardUserDefaults] setObject:originTime forKey:CacheLiveTimeKey]; 73 | } 74 | if (day<=0) { 75 | day = CacheLiveDate; 76 | } 77 | NSDate *sevenTime = [originTime dateByAddingTimeInterval:24*60*60*day]; 78 | 79 | NSDate *currentDateTime = [self beijingTime]; 80 | NSComparisonResult result = [currentDateTime compare:sevenTime]; 81 | 82 | if (result == NSOrderedDescending) { //时间超过设定的时间 83 | [self clearZGCache]; 84 | } 85 | } 86 | - (void)setDebugModel:(BOOL)boo { 87 | 88 | FileUtil *util = [FileUtil shared]; 89 | util.debug = boo; 90 | _debug = boo; 91 | 92 | } 93 | + (void)registerSchemeCache { 94 | [NSURLProtocol zg_registerScheme:@"http"]; 95 | [NSURLProtocol zg_registerScheme:@"https"]; 96 | } 97 | + (void)unRegisterSchemeCache { 98 | [NSURLProtocol zg_unregisterScheme:@"http"]; 99 | [NSURLProtocol zg_unregisterScheme:@"https"]; 100 | } 101 | #pragma mark - private method 102 | //拿到当前北京时间 103 | - (NSDate *)beijingTime { 104 | NSDate *date = [NSDate date]; 105 | NSTimeInterval inter = [[NSTimeZone systemTimeZone] secondsFromGMT]; 106 | return [date dateByAddingTimeInterval:inter]; 107 | } 108 | /** 109 | 得到MIME类型 110 | 111 | @param cacheKey 缓存key 112 | @return MIME类型 113 | */ 114 | - (NSString *)getMIMETypeFromKey:(NSString *)cacheKey { 115 | NSURL *url = [NSURL URLWithString:cacheKey]; 116 | NSString *keyValue = [url path]; 117 | 118 | NSDictionary *dic = [[NSUserDefaults standardUserDefaults] objectForKey:URLMIMETYPE]; 119 | NSString *mimeType = [dic objectForKey:keyValue]; 120 | 121 | if (mimeType) { 122 | return mimeType; 123 | } 124 | return nil; 125 | } 126 | 127 | @end 128 | -------------------------------------------------------------------------------- /ZGWKWebViewCache/main.m: -------------------------------------------------------------------------------- 1 | // 2 | // main.m 3 | // ZGWKWebViewCache 4 | // 5 | // Created by zhanggui on 2017/11/20. 6 | // Copyright © 2017年 zhanggui. All rights reserved. 7 | // 8 | 9 | #import 10 | #import "AppDelegate.h" 11 | 12 | int main(int argc, char * argv[]) { 13 | @autoreleasepool { 14 | return UIApplicationMain(argc, argv, nil, NSStringFromClass([AppDelegate class])); 15 | } 16 | } 17 | --------------------------------------------------------------------------------