forked from rs/SDURLCache
-
Notifications
You must be signed in to change notification settings - Fork 1
/
SDURLCache.m
647 lines (552 loc) · 23.7 KB
/
SDURLCache.m
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
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
//
// SDURLCache.m
// SDURLCache
//
// Created by Olivier Poitrey on 15/03/10.
// Copyright 2010 Dailymotion. All rights reserved.
//
#import "SDURLCache.h"
#import <CommonCrypto/CommonDigest.h>
static NSTimeInterval const kSDURLCacheInfoDefaultMinCacheInterval = 5 * 60; // 5 minute
static NSString *const kSDURLCacheInfoFileName = @"cacheInfo.plist";
static NSString *const kSDURLCacheInfoDiskUsageKey = @"diskUsage";
static NSString *const kSDURLCacheInfoAccessesKey = @"accesses";
static NSString *const kSDURLCacheInfoSizesKey = @"sizes";
static float const kSDURLCacheLastModFraction = 0.1f; // 10% since Last-Modified suggested by RFC2616 section 13.2.4
static float const kSDURLCacheDefault = 3600; // Default cache expiration delay if none defined (1 hour)
static BOOL verboseLogging = NO;
static NSDateFormatter* CreateDateFormatter(NSString *format)
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]];
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"GMT"]];
[dateFormatter setDateFormat:format];
return [dateFormatter autorelease];
}
@implementation NSCachedURLResponse(NSCoder)
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeDataObject:self.data];
[coder encodeObject:self.response forKey:@"response"];
[coder encodeObject:self.userInfo forKey:@"userInfo"];
[coder encodeInt:self.storagePolicy forKey:@"storagePolicy"];
}
- (id)initWithCoder:(NSCoder *)coder
{
return [self initWithResponse:[coder decodeObjectForKey:@"response"]
data:[coder decodeDataObject]
userInfo:[coder decodeObjectForKey:@"userInfo"]
storagePolicy:[coder decodeIntForKey:@"storagePolicy"]];
}
@end
@interface SDURLCache ()
@property (nonatomic, retain) NSString *diskCachePath;
@property (nonatomic, readonly) NSMutableDictionary *diskCacheInfo;
@property (nonatomic, retain) NSOperationQueue *ioQueue;
@property (retain) NSOperation *periodicMaintenanceOperation;
- (void)periodicMaintenance;
@end
@implementation SDURLCache
@synthesize diskCachePath, minCacheInterval, ioQueue, periodicMaintenanceOperation, ignoreMemoryOnlyStoragePolicy;
@dynamic diskCacheInfo;
#pragma mark SDURLCache (tools)
+ (NSURLRequest *)canonicalRequestForRequest:(NSURLRequest *)request
{
NSString *string = request.URL.absoluteString;
NSRange hash = [string rangeOfString:@"#"];
if (hash.location == NSNotFound)
return request;
NSMutableURLRequest *copy = [[request mutableCopy] autorelease];
copy.URL = [NSURL URLWithString:[string substringToIndex:hash.location]];
return copy;
}
+ (NSString *)cacheKeyForURL:(NSURL *)url
{
const char *str = [url.absoluteString UTF8String];
unsigned char r[CC_MD5_DIGEST_LENGTH];
CC_MD5(str, strlen(str), r);
return [NSString stringWithFormat:@"%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x%02x",
r[0], r[1], r[2], r[3], r[4], r[5], r[6], r[7], r[8], r[9], r[10], r[11], r[12], r[13], r[14], r[15]];
}
/*
* Parse HTTP Date: http://www.w3.org/Protocols/rfc2616/rfc2616-sec3.html#sec3.3.1
*/
+ (NSDate *)dateFromHttpDateString:(NSString *)httpDate
{
static NSDateFormatter *RFC1123DateFormatter;
static NSDateFormatter *ANSICDateFormatter;
static NSDateFormatter *RFC850DateFormatter;
NSDate *date = nil;
@synchronized(self) // NSDateFormatter isn't thread safe
{
// RFC 1123 date format - Sun, 06 Nov 1994 08:49:37 GMT
if (!RFC1123DateFormatter) RFC1123DateFormatter = [CreateDateFormatter(@"EEE, dd MMM yyyy HH:mm:ss z") retain];
date = [RFC1123DateFormatter dateFromString:httpDate];
if (!date)
{
// ANSI C date format - Sun Nov 6 08:49:37 1994
if (!ANSICDateFormatter) ANSICDateFormatter = [CreateDateFormatter(@"EEE MMM d HH:mm:ss yyyy") retain];
date = [ANSICDateFormatter dateFromString:httpDate];
if (!date)
{
// RFC 850 date format - Sunday, 06-Nov-94 08:49:37 GMT
if (!RFC850DateFormatter) RFC850DateFormatter = [CreateDateFormatter(@"EEEE, dd-MMM-yy HH:mm:ss z") retain];
date = [RFC850DateFormatter dateFromString:httpDate];
}
}
}
return date;
}
/*
* This method tries to determine the expiration date based on a response headers dictionary.
*/
+ (NSDate *)expirationDateFromHeaders:(NSDictionary *)headers withStatusCode:(NSInteger)status
{
if (status != 200 && status != 203 && status != 300 && status != 301 && status != 302 && status != 307 && status != 410)
{
if (verboseLogging)
NSLog(@"SDURLCache: uncacheable response status code %d", status);
return nil;
}
// Check Pragma: no-cache
NSString *pragma = [headers objectForKey:@"Pragma"];
if (pragma && [pragma isEqualToString:@"no-cache"])
{
if (verboseLogging)
NSLog(@"SDURLCache: Uncacheable due to headers %@.", pragma);
return nil;
}
// Define "now" based on the request
NSString *date = [headers objectForKey:@"Date"];
NSDate *now;
if (date)
{
now = [SDURLCache dateFromHttpDateString:date];
}
else
{
// If no Date: header, define now from local clock
now = [NSDate date];
}
// Look at info from the Cache-Control: max-age=n header
NSString *cacheControl = [headers objectForKey:@"Cache-Control"];
if (cacheControl)
{
NSRange foundRange = [cacheControl rangeOfString:@"no-store"];
if (foundRange.length > 0)
{
if (verboseLogging)
NSLog(@"SDURLCache: Headers disallow caching: %@",
cacheControl);
return nil;
}
NSInteger maxAge;
foundRange = [cacheControl rangeOfString:@"max-age="];
if (foundRange.length > 0)
{
NSScanner *cacheControlScanner = [NSScanner scannerWithString:cacheControl];
[cacheControlScanner setScanLocation:foundRange.location + foundRange.length];
if ([cacheControlScanner scanInteger:&maxAge])
{
if (maxAge > 0)
{
return [NSDate dateWithTimeIntervalSinceNow:maxAge];
}
else
{
if (verboseLogging)
NSLog(@"SDURLCache: Bad max-age= range (%@)",
cacheControl);
return nil;
}
}
}
}
// If not Cache-Control found, look at the Expires header
NSString *expires = [headers objectForKey:@"Expires"];
if (expires)
{
NSTimeInterval expirationInterval = 0;
NSDate *expirationDate = [SDURLCache dateFromHttpDateString:expires];
if (expirationDate)
{
expirationInterval = [expirationDate timeIntervalSinceDate:now];
}
if (expirationInterval > 0)
{
// Convert remote expiration date to local expiration date
return [NSDate dateWithTimeIntervalSinceNow:expirationInterval];
}
else
{
if (verboseLogging)
NSLog(@"SDURLCache: Expires header can't be parsed or is "
"expired, won't cache (%@)", expires);
return nil;
}
}
if (status == 302 || status == 307)
{
if (verboseLogging)
NSLog(@"SDURLCache: No explicit cache control for status %d, "
"not caching", status);
return nil;
}
// If no cache control defined, try some heristic to determine an expiration date
NSString *lastModified = [headers objectForKey:@"Last-Modified"];
if (lastModified)
{
NSTimeInterval age = 0;
NSDate *lastModifiedDate = [SDURLCache dateFromHttpDateString:lastModified];
if (lastModifiedDate)
{
// Define the age of the document by comparing the Date header with the Last-Modified header
age = [now timeIntervalSinceDate:lastModifiedDate];
}
if (age > 0)
{
return [NSDate dateWithTimeIntervalSinceNow:(age * kSDURLCacheLastModFraction)];
}
else
{
if (verboseLogging)
NSLog(@"SDURLCache: Last-Modified date suggest cache "
"expiration (%@)", lastModified);
return nil;
}
}
// If nothing permitted to define the cache expiration delay nor to restrict its cacheability, use a default cache expiration delay
return [[[NSDate alloc] initWithTimeInterval:kSDURLCacheDefault sinceDate:now] autorelease];
}
#pragma mark SDURLCache (private)
- (NSMutableDictionary *)diskCacheInfo
{
if (!diskCacheInfo)
{
@synchronized(self)
{
if (!diskCacheInfo) // Check again, maybe another thread created it while waiting for the mutex
{
diskCacheInfo = [[NSMutableDictionary alloc] initWithContentsOfFile:[diskCachePath stringByAppendingPathComponent:kSDURLCacheInfoFileName]];
if (!diskCacheInfo)
{
diskCacheInfo = [[NSMutableDictionary alloc] initWithObjectsAndKeys:
[NSNumber numberWithUnsignedInt:0], kSDURLCacheInfoDiskUsageKey,
[NSMutableDictionary dictionary], kSDURLCacheInfoAccessesKey,
[NSMutableDictionary dictionary], kSDURLCacheInfoSizesKey,
nil];
}
diskCacheInfoDirty = NO;
diskCacheUsage = [[diskCacheInfo
objectForKey:kSDURLCacheInfoDiskUsageKey]
intValue];
if (verboseLogging)
{
NSNumber *n = [diskCacheInfo objectForKey:kSDURLCacheInfoDiskUsageKey];
NSLog(@"SDURLCache diskCacheInfo initialisation, "
"disk usage: %d bytes, %0.2f MB.\n",
[n intValue], [n intValue] / (1024 * 1024.0));
}
diskCacheUsage = [[diskCacheInfo objectForKey:kSDURLCacheInfoDiskUsageKey] unsignedIntValue];
periodicMaintenanceTimer = [[NSTimer scheduledTimerWithTimeInterval:5
target:self
selector:@selector(periodicMaintenance)
userInfo:nil
repeats:YES] retain];
}
}
}
return diskCacheInfo;
}
- (void)createDiskCachePath
{
NSFileManager *fileManager = [[NSFileManager alloc] init];
if (![fileManager fileExistsAtPath:diskCachePath])
{
[fileManager createDirectoryAtPath:diskCachePath
withIntermediateDirectories:YES
attributes:nil
error:NULL];
}
[fileManager release];
}
- (void)saveCacheInfo
{
[self createDiskCachePath];
@synchronized(self.diskCacheInfo)
{
NSData *data = [NSPropertyListSerialization dataFromPropertyList:self.diskCacheInfo format:NSPropertyListBinaryFormat_v1_0 errorDescription:NULL];
if (data)
{
[data writeToFile:[diskCachePath stringByAppendingPathComponent:kSDURLCacheInfoFileName] atomically:YES];
}
diskCacheInfoDirty = NO;
}
}
- (void)removeCachedResponseForCachedKeys:(NSArray *)cacheKeys
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSEnumerator *enumerator = [cacheKeys objectEnumerator];
NSString *cacheKey;
@synchronized(self.diskCacheInfo)
{
NSMutableDictionary *accesses = [self.diskCacheInfo objectForKey:kSDURLCacheInfoAccessesKey];
NSMutableDictionary *sizes = [self.diskCacheInfo objectForKey:kSDURLCacheInfoSizesKey];
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
while ((cacheKey = [enumerator nextObject]))
{
NSUInteger cacheItemSize = [[sizes objectForKey:cacheKey] unsignedIntegerValue];
[accesses removeObjectForKey:cacheKey];
[sizes removeObjectForKey:cacheKey];
[fileManager removeItemAtPath:[diskCachePath stringByAppendingPathComponent:cacheKey] error:NULL];
diskCacheUsage -= cacheItemSize;
[self.diskCacheInfo setObject:[NSNumber numberWithUnsignedInteger:diskCacheUsage] forKey:kSDURLCacheInfoDiskUsageKey];
}
}
[pool drain];
}
- (void)balanceDiskUsage
{
if (diskCacheUsage < self.diskCapacity)
{
// Already done
return;
}
if (verboseLogging)
NSLog(@"SDURLCache: Applying cleaning algorithms to balance cache "
"disk usage");
NSMutableArray *keysToRemove = [NSMutableArray array];
@synchronized(self.diskCacheInfo)
{
// Apply LRU cache eviction algorithm while disk usage outreach capacity
NSDictionary *sizes = [self.diskCacheInfo objectForKey:kSDURLCacheInfoSizesKey];
NSInteger capacityToSave = diskCacheUsage - self.diskCapacity;
NSArray *sortedKeys = [[self.diskCacheInfo objectForKey:kSDURLCacheInfoAccessesKey] keysSortedByValueUsingSelector:@selector(compare:)];
NSEnumerator *enumerator = [sortedKeys objectEnumerator];
NSString *cacheKey;
while (capacityToSave > 0 && (cacheKey = [enumerator nextObject]))
{
[keysToRemove addObject:cacheKey];
capacityToSave -= [(NSNumber *)[sizes objectForKey:cacheKey] unsignedIntegerValue];
}
}
[self removeCachedResponseForCachedKeys:keysToRemove];
[self saveCacheInfo];
}
- (void)storeToDisk:(NSDictionary *)context
{
NSURLRequest *request = [context objectForKey:@"request"];
NSCachedURLResponse *cachedResponse = [context objectForKey:@"cachedResponse"];
NSString *cacheKey = [SDURLCache cacheKeyForURL:request.URL];
NSString *cacheFilePath = [diskCachePath stringByAppendingPathComponent:cacheKey];
[self createDiskCachePath];
// Archive the cached response on disk
if (![NSKeyedArchiver archiveRootObject:cachedResponse toFile:cacheFilePath])
{
if (verboseLogging)
NSLog(@"SDURLCache: Caching failed for some reason for request %@",
request.URL);
return;
}
// Update disk usage info
NSFileManager *fileManager = [[NSFileManager alloc] init];
NSNumber *cacheItemSize = [[fileManager attributesOfItemAtPath:cacheFilePath error:NULL] objectForKey:NSFileSize];
[fileManager release];
if (verboseLogging)
NSLog(@"SDURLCache: Caching %d bytes for %@",
[cacheItemSize unsignedIntValue], request.URL);
diskCacheUsage += [cacheItemSize unsignedIntegerValue];
@synchronized(self.diskCacheInfo)
{
diskCacheUsage += [cacheItemSize unsignedIntegerValue];
[self.diskCacheInfo setObject:[NSNumber numberWithUnsignedInteger:diskCacheUsage] forKey:kSDURLCacheInfoDiskUsageKey];
// Update cache info for the stored item
[(NSMutableDictionary *)[self.diskCacheInfo objectForKey:kSDURLCacheInfoAccessesKey] setObject:[NSDate date] forKey:cacheKey];
[(NSMutableDictionary *)[self.diskCacheInfo objectForKey:kSDURLCacheInfoSizesKey] setObject:cacheItemSize forKey:cacheKey];
}
[self saveCacheInfo];
}
- (void)periodicMaintenance
{
// If another same maintenance operation is already sceduled, cancel it so this new operation will be executed after other
// operations of the queue, so we can group more work together
[periodicMaintenanceOperation cancel];
self.periodicMaintenanceOperation = nil;
// If disk usage outrich capacity, run the cache eviction operation and if cacheInfo dictionnary is dirty, save it in an operation
if (diskCacheUsage > self.diskCapacity)
{
self.periodicMaintenanceOperation = [[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(balanceDiskUsage) object:nil] autorelease];
[ioQueue addOperation:periodicMaintenanceOperation];
}
else if (diskCacheInfoDirty)
{
self.periodicMaintenanceOperation = [[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(saveCacheInfo) object:nil] autorelease];
[ioQueue addOperation:periodicMaintenanceOperation];
}
}
#pragma mark SDURLCache
+ (NSString *)defaultCachePath
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
return [[paths objectAtIndex:0] stringByAppendingPathComponent:@"SDURLCache"];
}
- (BOOL)verboseLogging
{
return verboseLogging;
}
- (void)setVerboseLogging:(BOOL)value
{
verboseLogging = value;
}
#pragma mark NSURLCache
- (id)initWithMemoryCapacity:(NSUInteger)memoryCapacity diskCapacity:(NSUInteger)diskCapacity diskPath:(NSString *)path
{
if ((self = [super initWithMemoryCapacity:memoryCapacity diskCapacity:diskCapacity diskPath:path]))
{
self.minCacheInterval = kSDURLCacheInfoDefaultMinCacheInterval;
self.diskCachePath = path;
// Init the operation queue
self.ioQueue = [[[NSOperationQueue alloc] init] autorelease];
ioQueue.maxConcurrentOperationCount = 1; // used to streamline operations in a separate thread
self.ignoreMemoryOnlyStoragePolicy = YES;
}
return self;
}
- (void)storeCachedResponse:(NSCachedURLResponse *)cachedResponse forRequest:(NSURLRequest *)request
{
request = [SDURLCache canonicalRequestForRequest:request];
if (request.cachePolicy == NSURLRequestReloadIgnoringLocalCacheData
|| request.cachePolicy == NSURLRequestReloadIgnoringLocalAndRemoteCacheData
|| request.cachePolicy == NSURLRequestReloadIgnoringCacheData)
{
// When cache is ignored for read, it's a good idea not to store the result as well as this option
// have big chance to be used every times in the future for the same request.
// NOTE: This is a change regarding default URLCache behavior
return;
}
[super storeCachedResponse:cachedResponse forRequest:request];
NSURLCacheStoragePolicy storagePolicy = cachedResponse.storagePolicy;
if ((storagePolicy == NSURLCacheStorageAllowed || (storagePolicy == NSURLCacheStorageAllowedInMemoryOnly && ignoreMemoryOnlyStoragePolicy))
&& [cachedResponse.response isKindOfClass:[NSHTTPURLResponse self]]
&& cachedResponse.data.length < self.diskCapacity)
{
NSDictionary *headers = [(NSHTTPURLResponse *)cachedResponse.response allHeaderFields];
// RFC 2616 section 13.3.4 says clients MUST use Etag in any cache-conditional request if provided by server
if (![headers objectForKey:@"Etag"])
{
NSDate *expirationDate = [SDURLCache expirationDateFromHeaders:headers
withStatusCode:((NSHTTPURLResponse *)cachedResponse.response).statusCode];
if (!expirationDate || [expirationDate timeIntervalSinceNow] - minCacheInterval <= 0)
{
// This response is not cacheable, headers said
return;
}
}
[ioQueue addOperation:[[[NSInvocationOperation alloc] initWithTarget:self
selector:@selector(storeToDisk:)
object:[NSDictionary dictionaryWithObjectsAndKeys:
cachedResponse, @"cachedResponse",
request, @"request",
nil]] autorelease]];
}
}
- (NSCachedURLResponse *)cachedResponseForRequest:(NSURLRequest *)request
{
request = [SDURLCache canonicalRequestForRequest:request];
NSCachedURLResponse *memoryResponse = [super cachedResponseForRequest:request];
if (memoryResponse)
{
return memoryResponse;
}
NSString *cacheKey = [SDURLCache cacheKeyForURL:request.URL];
// NOTE: We don't handle expiration here as even staled cache data is necessary for NSURLConnection to handle cache revalidation.
// Staled cache data is also needed for cachePolicies which force the use of the cache.
@synchronized(self.diskCacheInfo)
{
NSMutableDictionary *accesses = [self.diskCacheInfo objectForKey:kSDURLCacheInfoAccessesKey];
if ([accesses objectForKey:cacheKey]) // OPTI: Check for cache-hit in a in-memory dictionnary before to hit the FS
{
NSCachedURLResponse *diskResponse = [NSKeyedUnarchiver unarchiveObjectWithFile:[diskCachePath stringByAppendingPathComponent:cacheKey]];
if (diskResponse)
{
// OPTI: Log the entry last access time for LRU cache eviction algorithm but don't save the dictionary
// on disk now in order to save IO and time
[accesses setObject:[NSDate date] forKey:cacheKey];
diskCacheInfoDirty = YES;
// OPTI: Store the response to memory cache for potential future requests
[super storeCachedResponse:diskResponse forRequest:request];
// SRK: Work around an interesting retainCount bug in CFNetwork on iOS << 3.2.
if (kCFCoreFoundationVersionNumber < kCFCoreFoundationVersionNumber_iPhoneOS_3_2)
{
diskResponse = [super cachedResponseForRequest:request];
}
if (diskResponse)
{
return diskResponse;
}
}
}
}
if (verboseLogging)
NSLog(@"SDURLCache: cache miss for %@", request.URL);
return nil;
}
- (NSUInteger)currentDiskUsage
{
if (!diskCacheInfo)
{
[self diskCacheInfo];
}
return diskCacheUsage;
}
- (void)removeCachedResponseForRequest:(NSURLRequest *)request
{
request = [SDURLCache canonicalRequestForRequest:request];
[super removeCachedResponseForRequest:request];
[self removeCachedResponseForCachedKeys:[NSArray arrayWithObject:[SDURLCache cacheKeyForURL:request.URL]]];
[self saveCacheInfo];
}
- (void)removeAllCachedResponses
{
if (verboseLogging)
{
NSLog(@"SDURLCache: purging disk cache.");
}
[super removeAllCachedResponses];
NSFileManager *fileManager = [[[NSFileManager alloc] init] autorelease];
[fileManager removeItemAtPath:diskCachePath error:NULL];
@synchronized(self)
{
[diskCacheInfo release], diskCacheInfo = nil;
}
}
- (BOOL)isCached:(NSURL *)url
{
NSURLRequest *request = [NSURLRequest requestWithURL:url];
request = [SDURLCache canonicalRequestForRequest:request];
if ([super cachedResponseForRequest:request])
{
return YES;
}
NSString *cacheKey = [SDURLCache cacheKeyForURL:url];
NSString *cacheFile = [diskCachePath stringByAppendingPathComponent:cacheKey];
if ([[[[NSFileManager alloc] init] autorelease] fileExistsAtPath:cacheFile])
{
return YES;
}
if (verboseLogging)
NSLog(@"SDURLCache: isCached miss for %@", url);
return NO;
}
#pragma mark NSObject
- (void)dealloc
{
[periodicMaintenanceTimer invalidate];
[periodicMaintenanceTimer release], periodicMaintenanceTimer = nil;
[periodicMaintenanceOperation release], periodicMaintenanceOperation = nil;
[diskCachePath release], diskCachePath = nil;
[diskCacheInfo release], diskCacheInfo = nil;
[ioQueue release], ioQueue = nil;
[super dealloc];
}
@end