YHURLCache.m
10.7 KB
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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
//
// YHURLCache.m
// YohoExplorerDemo
//
// Created by gaoqiang xu on 4/16/15.
// Copyright (c) 2015 gaoqiang xu. All rights reserved.
//
#import "YHURLCache.h"
#import <CommonCrypto/CommonDigest.h>
@interface YHURLCache ()
@property (copy, atomic) NSString *diskPath;
@property (atomic) NSInteger cacheDuration;
@property (strong, atomic) NSCache *memCache;
@property (strong, nonatomic) NSArray *cacheTypes;
@property (strong, nonatomic) NSMutableDictionary *webViewCacheUrls;
@end
@implementation YHURLCache
#pragma mark - Override
- (void)dealloc
{
[self.memCache removeAllObjects];
}
- (NSArray *)cacheTypes
{
if (!_cacheTypes) {
_cacheTypes = @[ @"jpg", @"jpeg", @"png", @"gif", @"html", @"css" ].mutableCopy;
}
return _cacheTypes;
}
- (instancetype)initWithMemoryCapacity:(NSUInteger)memoryCapacity
diskCapacity:(NSUInteger)diskCapacity
diskPath:(NSString *)path
cacheDuration:(NSInteger)cacheDuration
{
self = [self initWithMemoryCapacity:memoryCapacity diskCapacity:diskCapacity diskPath:path];
if (self) {
_cacheDuration = cacheDuration;
}
return self;
}
- (instancetype)initWithMemoryCapacity:(NSUInteger)memoryCapacity diskCapacity:(NSUInteger)diskCapacity diskPath:(NSString *)path
{
self = [super initWithMemoryCapacity:memoryCapacity diskCapacity:diskCapacity diskPath:path];
if (self) {
if (path) {
_diskPath = path;
} else {
_diskPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject];
}
_memCache = [[NSCache alloc] init];
_cacheDuration = 0;
}
return self;
}
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
if (request.cachePolicy == NSURLCacheStorageNotAllowed || [request.URL.absoluteString hasPrefix:@"file://"] || [request.URL.absoluteString hasPrefix:@"data:"]) {
return nil;
}
NSString *url = [self removeParams:request.URL.absoluteString];
NSString *extension = [[url pathExtension] lowercaseString];
NSArray *types = [self.cacheTypes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF = %@", extension]];
if ([request.HTTPMethod isEqualToString:@"GET"]
&& (types.count == 1 || [self existInCacheDictionary:request] )) {
return [self cachedDataForRequest:request];
} else {
return [super cachedResponseForRequest:request];
}
}
- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request
{
NSString *url = [self removeParams:request.URL.absoluteString];
NSString *extension = [[url pathExtension] lowercaseString];
NSArray *types = [self.cacheTypes filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF = %@", extension]];
if ([request.HTTPMethod isEqualToString:@"GET"]
&& (types.count == 1 || [self existInCacheDictionary:request] )) {
NSHTTPURLResponse *response = (NSHTTPURLResponse *)cachedResponse.response;
if (cachedResponse.response && cachedResponse.data && [response statusCode] == 200) {
NSDate *date = [NSDate date];
NSString *url = request.URL.absoluteString;
NSString *urlWithOtherInfo = [[NSString alloc] initWithFormat:@"%@-otherInfo", url];
NSString *filePath = [self cacheFilePath:[self md5Hash:url]];
NSString *otherInfoPath = [self cacheFilePath:[self md5Hash:urlWithOtherInfo]];
NSDictionary *dic;
if (cachedResponse.response.textEncodingName) {
dic = @{ @"time":[NSString stringWithFormat:@"%.0f", [date timeIntervalSince1970]],
@"MIMEType":cachedResponse.response.MIMEType,
@"textEncodingName":cachedResponse.response.textEncodingName };
} else {
dic = @{ @"time":[NSString stringWithFormat:@"%.0f", [date timeIntervalSince1970]],
@"MIMEType":cachedResponse.response.MIMEType };
}
[self.memCache setObject:cachedResponse.data forKey:[filePath lastPathComponent]];
[self.memCache setObject:dic forKey:[otherInfoPath lastPathComponent]];
[dic writeToFile:otherInfoPath atomically:YES];
[cachedResponse.data writeToFile:filePath atomically:YES];
}
} else {
[super storeCachedResponse:cachedResponse forRequest:request];
}
}
- (void)removeAllCachedResponses
{
[super removeAllCachedResponses];
[self deleteCacheFolder];
[self.memCache removeAllObjects];
}
- (void)removeCachedResponseForRequest:(NSURLRequest *)request
{
[super removeCachedResponseForRequest:request];
NSString *url = request.URL.absoluteString;
NSString *urlWithOtherInfo = [[NSString alloc] initWithFormat:@"%@-otherInfo", url];
NSString *filePath = [self cacheFilePath:[self md5Hash:url]];
NSString *otherInfoPath = [self cacheFilePath:[self md5Hash:urlWithOtherInfo]];
[self.memCache removeObjectForKey:[filePath lastPathComponent]];
[self.memCache removeObjectForKey:[otherInfoPath lastPathComponent]];
NSFileManager *fm = [[NSFileManager alloc] init];
[fm removeItemAtPath:filePath error:nil];
[fm removeItemAtPath:otherInfoPath error:nil];
}
#pragma mark - Setter & Getter
- (NSMutableDictionary *)webViewCacheUrls
{
if (!_webViewCacheUrls) {
_webViewCacheUrls = @{}.mutableCopy;
}
return _webViewCacheUrls;
}
#pragma mark - Private
- (NSString *)removeParams:(NSString *)url
{
NSString *freshUrl = url;
NSRange rangeQ = [url rangeOfString:@"?"];
if (rangeQ.location != NSNotFound) {
freshUrl = [url substringToIndex:rangeQ.location];
}
return freshUrl;
}
- (BOOL)existInCacheDictionary:(NSURLRequest *)request
{
BOOL existCacheUrl = NO;
for (id object in [self.webViewCacheUrls allKeys]) {
NSArray *temp = self.webViewCacheUrls[object];
for (NSString *url in temp) {
if ([url isEqualToString:request.URL.absoluteString]) {
existCacheUrl = YES;
break;
}
}
if (existCacheUrl) {
break;
}
}
return existCacheUrl;
}
- (NSString *)md5Hash:(NSString *)str
{
const char *cStr = [str UTF8String];
unsigned char result[16];
CC_MD5(cStr, (unsigned int)strlen(cStr), result);
NSString *md5Result = [NSString stringWithFormat:
@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
result[0], result[1], result[2], result[3],
result[4], result[5], result[6], result[7],
result[8], result[9], result[10], result[11],
result[12], result[13], result[14], result[15]
];
return md5Result;
}
- (NSString *)cacheFolder
{
return @"yh_url_cache";
}
- (void)deleteCacheFolder
{
NSString *path = [NSString stringWithFormat:@"%@/%@", self.diskPath, [self cacheFolder]];
NSFileManager *fileManager = [[NSFileManager alloc] init];
[fileManager removeItemAtPath:path error:nil];
}
- (NSString *)cacheFilePath:(NSString *)fileName
{
NSString *path = [[NSString alloc] initWithFormat:@"%@/%@", self.diskPath, self.cacheFolder];
NSFileManager *fm = [[NSFileManager alloc] init];
BOOL isDir;
if ([fm fileExistsAtPath:path isDirectory:&isDir] && isDir) {
} else {
[fm createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:nil];
}
return [path stringByAppendingPathComponent:fileName];
}
- (NSCachedURLResponse *)cachedDataForRequest:(NSURLRequest *)request
{
NSString *url = request.URL.absoluteString;
NSString *urlWithOtherInfo = [[NSString alloc] initWithFormat:@"%@-otherInfo", url];
NSString *filePath = [self cacheFilePath:[self md5Hash:url]];
NSString *otherInfoPath = [self cacheFilePath:[self md5Hash:urlWithOtherInfo]];
NSDate *date = [NSDate date];
NSFileManager *fm = [[NSFileManager alloc] init];
if ([fm fileExistsAtPath:filePath]) {
BOOL expire = NO;
NSDictionary *otherInfo = [self.memCache objectForKey:[otherInfoPath lastPathComponent]];
if (!otherInfo) {
otherInfo = [[NSDictionary alloc] initWithContentsOfFile:otherInfoPath];
if (otherInfo) {
[self.memCache setObject:otherInfo forKey:[otherInfoPath lastPathComponent]];
}
}
if (self.cacheDuration > 0) {
NSInteger createTime = [otherInfo[@"time"] integerValue];
if (createTime + self.cacheDuration < date.timeIntervalSince1970) {
expire = YES;
}
}
if (!expire) {
// Getting data from cache
NSData *data = [self.memCache objectForKey:[filePath lastPathComponent]];
if (!data) {
data = [[NSData alloc] initWithContentsOfFile:filePath];
if (data) {
[self.memCache setObject:data forKey:[filePath lastPathComponent]];
}
}
NSURLResponse *response = [[NSURLResponse alloc] initWithURL:request.URL
MIMEType:otherInfo[@"MIMEType"]
expectedContentLength:data.length
textEncodingName:otherInfo[@"textEncodingName"]];
NSCachedURLResponse *cachedResponse = [[NSCachedURLResponse alloc] initWithResponse:response data:data];
return cachedResponse;
} else {
// Removing old data
[fm removeItemAtPath:filePath error:nil];
[fm removeItemAtPath:otherInfoPath error:nil];
[self.memCache removeObjectForKey:[filePath lastPathComponent]];
[self.memCache removeObjectForKey:[otherInfoPath lastPathComponent]];
}
}
return nil;
}
#pragma mark - Public
- (void)addCacheUrl:(NSString *)url forKey:(id)object
{
NSMutableArray *array = self.webViewCacheUrls[object];
if (!array) {
array = @[].mutableCopy;
self.webViewCacheUrls[object] = array;
}
if (array.count == 0
|| [array filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF = %@", url]].count == 0) {
[array addObject:url];
}
}
- (void)removeUrlsForKey:(id)object
{
[self.webViewCacheUrls removeObjectForKey:object];
}
@end