-
Notifications
You must be signed in to change notification settings - Fork 1
/
TLNonBlockingCache.m
323 lines (279 loc) · 10.4 KB
/
TLNonBlockingCache.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
//
// TLNonBlockingCache.m
// TLCommon
//
// Created by Joshua Bleecher Snyder on 9/8/09.
//
#import "TLNonBlockingCache.h"
#import "TLNonBlockingCacheDelegate.h"
#import "NSFileManager_TLCommon.h"
#import "UIApplication_TLCommon.h"
#define kCacheFolder @"TLNonBlockingCache"
#define kResultDictionaryKeyError @"error"
#define kResultDictionaryKeyData @"dataPath"
#define kDeleteDetailsKeyDomain @"domain"
#define kDeleteDetailsKeyTTL @"ttl"
#pragma mark -
@interface TLNonBlockingCache ()
- (NSString *)dataPath;
+ (NSString *)pathForDomain:(NSString *)aDomain;
+ (NSString *)pathForDomain:(NSString *)aDomain name:(NSString *)aName;
+ (BOOL)fileAtPath:(NSString *)path isExpired:(NSTimeInterval)ttl;
- (void)fetchNewData;
- (void)fetchNewDataBlocking:(NSURL *)dataURL;
- (void)fetchDidCompleteWithResult:(NSDictionary *)result;
+ (void)deleteExpiredFilesBlockingWithDetails:(NSDictionary *)deleteDetails;
@property(nonatomic, assign, readwrite) BOOL cancelled;
@property(nonatomic, retain, readwrite) NSString *domain;
@property(nonatomic, retain, readwrite) NSString *name;
@property(nonatomic, retain, readwrite) NSURL *dataSource;
@property(nonatomic, retain, readwrite) NSData *data;
@property(nonatomic, retain, readwrite) NSError *error;
@property(nonatomic, assign, readwrite) NSTimeInterval ttl;
@property(nonatomic, assign, readwrite) BOOL useStaleData;
@property(nonatomic, assign, readwrite) BOOL loading;
@end
#pragma mark -
@implementation TLNonBlockingCache
@synthesize domain;
@synthesize name;
@synthesize dataSource;
@synthesize data;
@synthesize error;
@synthesize ttl;
@synthesize useStaleData;
@synthesize delegate;
@synthesize cancelled;
@synthesize loading;
+ (void)deleteExpiredFilesInDomain:(NSString *)aDomain usingTtl:(NSTimeInterval)expiry {
if(!aDomain) {
return;
}
NSNumber *ttl = [NSNumber numberWithDouble:expiry];
NSDictionary *details = [NSDictionary dictionaryWithObjectsAndKeys:
aDomain, kDeleteDetailsKeyDomain,
ttl, kDeleteDetailsKeyTTL,
nil];
[self performSelectorInBackground:@selector(deleteExpiredFilesBlockingWithDetails:) withObject:details];
}
+ (void)deleteCachedDataForDomain:(NSString *)aDomain name:(NSString *)aName {
NSError *error = nil;
NSString *path = [self pathForDomain:aDomain name:aName];
[[NSFileManager defaultManager] removeItemAtPath:path error:&error];
if(error) {
/*
TLDebugLog(@"Filed to clean up expired file %@, could not delete, error %@: %@",
path,
error,
error.userInfo);
*/
}
}
+ (void)storeData:(NSData *)data forDomain:(NSString *)aDomain name:(NSString *)aName {
NSString *path = [self pathForDomain:aDomain name:aName];
[data writeToFile:path atomically:YES];
}
+ (void)deleteExpiredFilesBlockingWithDetails:(NSDictionary *)deleteDetails {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSString *domain = [deleteDetails objectForKey:kDeleteDetailsKeyDomain];
NSTimeInterval ttl = [[deleteDetails objectForKey:kDeleteDetailsKeyTTL] doubleValue];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSString *domainPath = [self pathForDomain:domain];
NSError *error = nil;
NSArray *namesInDomain = [fileManager contentsOfDirectoryAtPath:domainPath error:&error];
if(error) {
// Something went wrong, just log and bail
/*
TLDebugLog(@"Failed to clean up expired files in %@, could not read directory contents, error %@: %@",
domainPath,
error,
error.userInfo);
*/
} else {
// Step through each file, deleting if expired
for(NSString *name in namesInDomain) {
NSString *completePath = [domainPath stringByAppendingPathComponent:name];
if([self fileAtPath:completePath isExpired:ttl]) {
// Delete!
[fileManager removeItemAtPath:completePath error:&error];
if(error) {
/*
TLDebugLog(@"Filed to clean up expired file %@, could not delete, error %@: %@",
completePath,
error,
error.userInfo);
*/
}
}
}
}
[pool release];
}
- (id)initWithDomain:(NSString *)aDomain
name:(NSString *)aName
dataSource:(NSURL *)aDataSource
ttl:(NSTimeInterval)expiry
useStaleData:(BOOL)useStaleDataInsteadOfReturningNil
delegate:(id<TLNonBlockingCacheDelegate>)aDelegate {
if(self = [super init]) {
self.domain = aDomain;
self.name = aName;
self.dataSource = aDataSource;
self.ttl = expiry;
self.useStaleData = useStaleDataInsteadOfReturningNil;
self.delegate = aDelegate;
NSString *dataPath = [self dataPath];
NSFileManager *fileManager = [NSFileManager defaultManager];
if([fileManager fileExistsAtPath:dataPath]) {
// There's data, is it stale?
if(![[self class] fileAtPath:dataPath isExpired:self.ttl]) {
// Not stale, we're done
self.data = [NSData dataWithContentsOfFile:dataPath];
} else {
// Stale; either return nil or the stale data, per preferences,
// and then start a fetch
if(self.useStaleData) {
self.data = [NSData dataWithContentsOfFile:dataPath];
}
[self fetchNewData];
}
} else {
// No data at all, start a fetch
[self fetchNewData];
}
if(!self.data) {
// If we have no data, give them their default data back
if([self.delegate respondsToSelector:@selector(defaultDataForCache:)]) {
[[self retain] autorelease];
self.data = [delegate defaultDataForCache:self];
}
}
}
return self;
}
+ (BOOL)fileAtPath:(NSString *)path isExpired:(NSTimeInterval)expiryTtl {
NSDate *modificationDate = [[[NSFileManager defaultManager] fileAttributesAtPath:path
traverseLink:NO]
fileModificationDate];
return ([modificationDate timeIntervalSinceNow] < -expiryTtl);
}
+ (NSString *)pathForDomain:(NSString *)aDomain {
NSString *domainPath = [NSFileManager applicationDocumentsDirectory];
domainPath = [domainPath stringByAppendingPathComponent:kCacheFolder];
domainPath = [domainPath stringByAppendingPathComponent:aDomain];
return domainPath;
}
+ (NSString *)pathForDomain:(NSString *)aDomain name:(NSString *)aName {
NSString *domainPath = [self pathForDomain:aDomain];
return [domainPath stringByAppendingPathComponent:aName];
}
- (NSString *)dataPath {
return [[self class] pathForDomain:self.domain name:self.name];
}
- (void)fetchNewData {
[self retain]; // stay alive until we're done!
self.loading = YES;
[[UIApplication sharedApplication] didStartNetworkRequest];
[self performSelectorInBackground:@selector(fetchNewDataBlocking:) withObject:self.dataSource];
}
- (void)fetchNewDataBlocking:(NSURL *)dataURL {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSURLRequest *request = [NSURLRequest requestWithURL:dataURL];
NSURLResponse *response = nil;
NSError *requestError = nil;
NSData *responseData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&requestError];
if([response isKindOfClass:[NSHTTPURLResponse class]]) {
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)response;
if([httpResponse statusCode] / 100 != 2) {
// not a 2xx response, fail by zeroing out the data, since it is just junk error text
responseData = nil;
}
}
id returnError = nil;
if(requestError) {
returnError = requestError;
} else {
returnError = [NSNull null];
}
id returnData = nil;
if(responseData) {
returnData = responseData;
} else {
returnData = [NSNull null];
}
NSDictionary *returnValue = [NSDictionary dictionaryWithObjectsAndKeys:
returnError, kResultDictionaryKeyError,
returnData, kResultDictionaryKeyData,
nil];
[self performSelectorOnMainThread:@selector(fetchDidCompleteWithResult:) withObject:returnValue waitUntilDone:NO];
[pool release];
}
- (void)cancel {
self.cancelled = YES;
}
- (void)fetchDidCompleteWithResult:(NSDictionary *)result {
[[UIApplication sharedApplication] didStopNetworkRequest];
self.loading = NO;
if(self.cancelled) {
return;
}
id errorField = [result objectForKey:kResultDictionaryKeyError];
self.error = (errorField == [NSNull null]) ? nil : (NSError *)errorField;
id dataField = [result objectForKey:kResultDictionaryKeyData];
NSData *receivedData = (dataField == [NSNull null]) ? nil : dataField;
[[self retain] autorelease];
if(self.error || !receivedData) {
// Report error
if([self.delegate respondsToSelector:@selector(cacheDidFailToReceiveFreshData:)]) {
[self.delegate cacheDidFailToReceiveFreshData:self];
}
} else {
BOOL shouldStoreData = YES;
// We've got data -- verify it now
if([self.delegate respondsToSelector:@selector(cache:shouldStoreData:)]) {
shouldStoreData = [self.delegate cache:self
shouldStoreData:receivedData];
}
if(shouldStoreData) {
self.data = receivedData;
// Save new data and report success
// Make sure the directory exists
[[NSFileManager defaultManager] createDirectoryAtPath:[[self class] pathForDomain:self.domain]
withIntermediateDirectories:YES
attributes:nil
error:NULL];
// Write the data
[self.data writeToFile:[self dataPath] atomically:YES];
if([self.delegate respondsToSelector:@selector(cacheDidReceiveFreshData:)]) {
[self.delegate cacheDidReceiveFreshData:self];
}
} else {
// Report error
if([self.delegate respondsToSelector:@selector(cacheDidFailToReceiveFreshData:)]) {
[self.delegate cacheDidFailToReceiveFreshData:self];
}
}
}
[self release]; // matches retain in fetchNewData
}
- (NSString *)description {
return [NSString stringWithFormat:@"<%@ %p: %@-%@ (%@)>",
NSStringFromClass([self class]),
self,
self.domain,
self.name,
self.dataSource];
}
- (void)dealloc {
[domain release];
domain = nil;
[name release];
name = nil;
[dataSource release];
dataSource = nil;
[data release];
data = nil;
delegate = nil;
[super dealloc];
}
@end