forked from mll/MLImageCache
-
Notifications
You must be signed in to change notification settings - Fork 0
/
MLImageCache.m
289 lines (228 loc) · 10.9 KB
/
MLImageCache.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
//
// MLImageCache.m
//
/* Copyright (c) 2014 Marek Lipert <[email protected]>
Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is furnished
to do so, subject to the following conditions:
The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE. */
#import "MLImageCache.h"
#import <CommonCrypto/CommonDigest.h>
#import <objc/runtime.h>
@interface MLImageCache()
@property(nonatomic,strong) NSOperationQueue *downloadQueue;
@property(nonatomic,strong) NSMutableDictionary *cache;
@property(nonatomic,strong) NSString *cacheDir;
@property(nonatomic,strong) NSMutableDictionary *downloadReferences;
- (NSString *)MD5FromData:(NSData *)data;
- (NSString *)MD5FromString:(NSString *)string;
@end
static char associationKey;
@implementation MLImageCache
+ (MLImageCache *)sharedInstance {
static dispatch_once_t onceToken;
static MLImageCache *cache;
dispatch_once(&onceToken, ^{
cache = [[MLImageCache alloc] init];
});
return cache;
}
- (id)init {
self = [super init];
if(self) {
__weak MLImageCache *weakSelf = self;
NSAssert([NSThread isMainThread],@"Not on main thread");
self.downloadQueue = [NSOperationQueue new];
self.downloadQueue.maxConcurrentOperationCount = kNumberOfSimultaneousDownloads;
self.cache = [NSMutableDictionary new];
self.cacheDir = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSAssert(self.cacheDir,@"No caches directory");
self.downloadReferences = [NSMutableDictionary dictionary];
[[NSNotificationCenter defaultCenter] addObserverForName:UIApplicationDidReceiveMemoryWarningNotification object:nil queue:nil usingBlock:^(NSNotification *note) {
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(@"Image cache cleared itself after memory warning");
[weakSelf.cache removeAllObjects];
});
}];
}
return self;
}
- (BOOL) cacheImage:(UIImage *)image withUrl:(NSURL *)url
{
return [self cacheData:UIImagePNGRepresentation(image) withUrl:url];
}
- (BOOL) cacheData:(NSData *)data withUrl:(NSURL *)url
{
NSAssert([NSThread isMainThread],@"Not on main thread");
NSString *md5 = [self MD5FromString:url.absoluteString];
NSString *path = [self.cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.dat",md5]];
[self.cache setObject:data forKey:md5];
return [data writeToFile:path atomically:YES];
}
- (BOOL) prefetchFromURL: (NSURL *)url
{
NSAssert([NSThread isMainThread],@"Not on main thread");
NSParameterAssert(url.absoluteString.length);
NSString *md5 = [self MD5FromString:url.absoluteString];
NSData *retVal = [self.cache objectForKey:md5];
NSString *path = [self.cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.dat",md5]];
if(!retVal) {
retVal = [NSData dataWithContentsOfFile:path];
if(retVal) {
[self.cache setObject:retVal forKey:md5];
}
}
return nil != retVal;
}
- (void) getImageAtURL: (NSURL *)url withPriority:(NSOperationQueuePriority) priority completion:(void(^)(UIImage *image, id referenceObject,BOOL loadedFromCache)) completion referenceObject: (id) reference {
[self getDataAtURL:url withPriority:priority completion:^(NSData *data, id referenceObject,BOOL loadedFromCache) {
if(data) {
UIImage *image = [UIImage imageWithData:data];
if(completion) completion(image,reference,loadedFromCache);
}
} referenceObject:reference];
}
- (void) getDataAtURL: (NSURL *)url withPriority:(NSOperationQueuePriority) priority completion:(void(^)(NSData *data, id referenceObject,BOOL loadedFromCache)) completion referenceObject: (id) reference
{
NSAssert([NSThread isMainThread],@"Not on main thread");
NSParameterAssert(url.absoluteString.length);
NSParameterAssert(completion);
NSString *md5 = [self MD5FromString:url.absoluteString];
NSAssert(md5.length,@"No md5");
if(!reference) reference = [NSNull null];
NSNumber *revision = objc_getAssociatedObject(reference, &associationKey);
if(revision) {
revision = @(revision.integerValue+1);
} else {
revision = @0;
}
objc_setAssociatedObject(reference, &associationKey, revision, OBJC_ASSOCIATION_RETAIN);
__block NSData *retVal = [self.cache objectForKey:md5];
NSString *path = [self.cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.dat",md5]];
__weak MLImageCache *weakSelf = self;
if(retVal)
{
completion(retVal,reference,YES);
return;
}
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
BOOL readFromFile = NO;
if(!retVal) {
retVal = [NSData dataWithContentsOfFile:path];
if(retVal) {
readFromFile = YES;
}
}
__weak id weakReference = reference;
dispatch_async(dispatch_get_main_queue(), ^{
if(retVal) {
if(readFromFile) [weakSelf.cache setObject:retVal forKey:md5];
completion(retVal,weakReference,YES);
return; /* we assume that image at url never changes */
}
NSMutableArray *referenceArray = weakSelf.downloadReferences[md5];
if(referenceArray.count) {
[referenceArray addObject:@{@"reference" : reference, @"revision" : [revision copy],@"completion":[completion copy]}];
return;
}
referenceArray = [NSMutableArray array];
weakSelf.downloadReferences[md5] = referenceArray;
[referenceArray addObject:@{@"reference" : reference, @"revision" : [revision copy], @"completion":[completion copy]}];
[weakSelf downloadDataAtUrl:url withPriority:priority completion:^(NSData *data, id referenceObject) {
if(data) {
[weakSelf.cache setObject:data forKey:md5];
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), ^{
BOOL success = NO;
NSString *path = [weakSelf.cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.dat",md5]];
success = [data writeToFile:path atomically:YES];
NSAssert(success, @"An error occurred when writing the image into the file path");
});
}
NSMutableArray *internalReferences = self.downloadReferences[md5];
NSParameterAssert(internalReferences);
for(NSDictionary *d in internalReferences) {
id object = d[@"reference"];
NSNumber *internal = objc_getAssociatedObject(object, &associationKey);
NSNumber *rev = d[@"revision"];
void(^internalCompletion)(NSData *data, id referenceObject,BOOL loadedFromCache) = d[@"completion"];
if([internal isEqual:rev] || [object isKindOfClass:[NSNull class]]) {
objc_setAssociatedObject(object, &associationKey, nil, OBJC_ASSOCIATION_RETAIN);
internalCompletion(data,object,NO);
}
}
[weakSelf.downloadReferences removeObjectForKey:md5];
} referenceObject:weakReference];
});
});
}
- (BOOL) removeImageForURL:(NSURL *)url {
NSString *md5 = [self MD5FromString:url.absoluteString];
__block NSData *retVal = [self.cache objectForKey:md5];
if (retVal) {
[self.cache removeObjectForKey:md5];
NSString *path = [self.cacheDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.dat",md5]];
NSError *error;
BOOL success = [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
if (error) {
NSLog(@"Error removing object: %@",error);
}
return success;
}
return NO;
}
#pragma mark - Utilities
- (void) downloadDataAtUrl: (NSURL *)url withPriority: (NSOperationQueuePriority) priority completion: (void(^)(NSData *data, id referenceObject)) completion referenceObject: (id) reference {
NSParameterAssert(url);
NSParameterAssert(completion);
__weak id weakReference = reference;
NSOperation *op = [NSBlockOperation blockOperationWithBlock:^{
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
dispatch_sync(dispatch_get_main_queue(), ^{
id strongReference = weakReference;
completion(data,strongReference);
});
}];
op.queuePriority = priority;
[self.downloadQueue addOperation:op];
}
- (NSString*)MD5FromData:(NSData *)data
{
// Create byte array of unsigned chars
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
// Create 16 byte MD5 hash value, store in buffer
CC_MD5(data.bytes, (unsigned int)data.length, md5Buffer);
// Convert unsigned char buffer to NSString of hex values
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x",md5Buffer[i]];
return output;
}
- (NSString*)MD5FromString:(NSString *)string
{
// Create pointer to the string as UTF8
const char *ptr = [string UTF8String];
// Create byte array of unsigned chars
unsigned char md5Buffer[CC_MD5_DIGEST_LENGTH];
// Create 16 byte MD5 hash value, store in buffer
CC_MD5(ptr, (unsigned int)strlen(ptr), md5Buffer);
// Convert MD5 value in the buffer to NSString of hex values
NSMutableString *output = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH * 2];
for(int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[output appendFormat:@"%02x",md5Buffer[i]];
return output;
}
@end