/
NYXProgressiveImageView.m
416 lines (361 loc) · 11.3 KB
/
NYXProgressiveImageView.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
//
// NYXProgressiveImageView.m
// NYXImagesKit
//
// Created by @Nyx0uf on 13/01/12.
// Copyright 2012 Nyx0uf. All rights reserved.
// www.cocoaintheshell.com
// Caching stuff by raphaelp
//
#import "NYXProgressiveImageView.h"
#import "NYXImagesHelper.h"
//#import "UIImage+Saving.h"
#import <ImageIO/ImageIO.h>
#import <CommonCrypto/CommonDigest.h>
#define kNyxDefaultCacheTimeValue 604800.0f // 7 days
#define kNyxDefaultTimeoutValue 10.0f
typedef struct
{
unsigned int delegateImageDidLoadWithImage:1;
unsigned int delegateImageDownloadCompletedWithImage:1;
unsigned int delegateImageDownloadFailedWithData:1;
} NyxDelegateFlags;
@interface NYXProgressiveImageView()
-(void)initializeAttributes;
-(CGImageRef)createTransitoryImage:(CGImageRef)partialImage CF_RETURNS_RETAINED;
+(NSString*)cacheDirectoryAddress;
-(NSString*)cachedImageSystemName;
-(void)resetCache;
+(UIImageOrientation)exifOrientationToiOSOrientation:(int)exifOrientation;
@end
@implementation NYXProgressiveImageView
{
/// Image download connection
NSURLConnection* _connection;
/// Downloaded data
NSMutableData* _dataTemp;
/// Image source for progressive display
CGImageSourceRef _imageSource;
/// Width of the downloaded image
int _imageWidth;
/// Height of the downloaded image
int _imageHeight;
/// Expected image size
long long _expectedSize;
/// Image orientation
UIImageOrientation _imageOrientation;
/// Connection queue
dispatch_queue_t _queue;
/// Url
NSURL* _url;
/// Delegate flags, avoid to many respondsToSelector
NyxDelegateFlags _delegateFlags;
}
@synthesize delegate = _delegate;
@synthesize caching = _caching;
@synthesize cacheTime = _cacheTime;
@synthesize downloading = _downloading;
#pragma mark - Allocations / Deallocations
-(id)init
{
if ((self = [super init]))
{
[self initializeAttributes];
}
return self;
}
-(id)initWithCoder:(NSCoder*)aDecoder
{
if ((self = [super initWithCoder:aDecoder]))
{
[self initializeAttributes];
}
return self;
}
-(id)initWithFrame:(CGRect)frame
{
if ((self = [super initWithFrame:frame]))
{
[self initializeAttributes];
}
return self;
}
-(id)initWithImage:(UIImage*)image
{
if ((self = [super initWithImage:image]))
{
[self initializeAttributes];
}
return self;
}
-(id)initWithImage:(UIImage*)image highlightedImage:(UIImage*)highlightedImage
{
if ((self = [super initWithImage:image highlightedImage:highlightedImage]))
{
[self initializeAttributes];
}
return self;
}
-(void)dealloc
{
NYX_DISPATCH_RELEASE(_queue);
_queue = NULL;
}
#pragma mark - Public
-(void)setDelegate:(id<NYXProgressiveImageViewDelegate>)delegate
{
if (delegate != _delegate)
{
_delegate = delegate;
_delegateFlags.delegateImageDidLoadWithImage = (unsigned)[delegate respondsToSelector:@selector(imageDidLoadWithImage:)];
_delegateFlags.delegateImageDownloadCompletedWithImage = (unsigned)[delegate respondsToSelector:@selector(imageDownloadCompletedWithImage:)];
_delegateFlags.delegateImageDownloadFailedWithData = (unsigned)[delegate respondsToSelector:@selector(imageDownloadFailedWithData:)];
}
}
-(void)loadImageAtURL:(NSURL*)url
{
if (_downloading)
return;
_url = url;
if (_caching)
{
NSFileManager* fileManager = [[NSFileManager alloc] init];
// check if file exists on cache
NSString* cacheDir = [NYXProgressiveImageView cacheDirectoryAddress];
NSString* cachedImagePath = [cacheDir stringByAppendingPathComponent:[self cachedImageSystemName]];
if ([fileManager fileExistsAtPath:cachedImagePath])
{
NSDate* mofificationDate = [[fileManager attributesOfItemAtPath:cachedImagePath error:nil] objectForKey:NSFileModificationDate];
// check modification date
if (-[mofificationDate timeIntervalSinceNow] > _cacheTime)
{
// Removes old cache file...
[self resetCache];
}
else
{
// Loads image from cache without networking
UIImage* localImage = [[UIImage alloc] initWithContentsOfFile:cachedImagePath];
dispatch_async(dispatch_get_main_queue(), ^{
self.image = localImage;
if (_delegateFlags.delegateImageDidLoadWithImage)
[_delegate imageDidLoadWithImage:localImage];
});
return;
}
}
}
dispatch_async(_queue, ^{
NSURLRequest* request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:kNyxDefaultTimeoutValue];
_connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[_connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
_downloading = YES;
[_connection start];
CFRunLoopRun();
});
}
+(void)resetImageCache
{
[[NSFileManager defaultManager] removeItemAtPath:[NYXProgressiveImageView cacheDirectoryAddress] error:nil];
}
#pragma mark - NSURLConnectionDelegate
-(void)connection:(__unused NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response
{
_imageSource = CGImageSourceCreateIncremental(NULL);
_imageWidth = _imageHeight = -1;
_expectedSize = [response expectedContentLength];
_dataTemp = [[NSMutableData alloc] init];
}
-(void)connection:(__unused NSURLConnection*)connection didReceiveData:(NSData*)data
{
[_dataTemp appendData:data];
const long long len = (long long)[_dataTemp length];
CGImageSourceUpdateData(_imageSource, (__bridge CFDataRef)_dataTemp, (len == _expectedSize) ? true : false);
if (_imageHeight > 0 && _imageWidth > 0)
{
CGImageRef cgImage = CGImageSourceCreateImageAtIndex(_imageSource, 0, NULL);
if (cgImage)
{
//if (NYX_IOS_VERSION_LESS_THAN(@"5.0"))
//{
/// iOS 4.x fix to correctly handle JPEG images ( http://www.cocoaintheshell.com/2011/05/progressive-images-download-imageio/ )
/// If the image doesn't have a transparency layer, the background is black-filled
/// So we still need to render the image, it's teh sux.
/// Note: Progressive JPEG are not supported see #32
CGImageRef imgTmp = [self createTransitoryImage:cgImage];
if (imgTmp)
{
__block UIImage* img = [[UIImage alloc] initWithCGImage:imgTmp scale:1.0f orientation:_imageOrientation];
CGImageRelease(imgTmp);
dispatch_async(dispatch_get_main_queue(), ^{
self.image = img;
});
}
//}
//else
//{
//__block UIImage* img = [[UIImage alloc] initWithCGImage:cgImage];
//dispatch_async(dispatch_get_main_queue(), ^{
//self.image = img;
//});
//}
CGImageRelease(cgImage);
}
}
else
{
CFDictionaryRef dic = CGImageSourceCopyPropertiesAtIndex(_imageSource, 0, NULL);
if (dic)
{
CFTypeRef val = CFDictionaryGetValue(dic, kCGImagePropertyPixelHeight);
if (val)
CFNumberGetValue(val, kCFNumberIntType, &_imageHeight);
val = CFDictionaryGetValue(dic, kCGImagePropertyPixelWidth);
if (val)
CFNumberGetValue(val, kCFNumberIntType, &_imageWidth);
val = CFDictionaryGetValue(dic, kCGImagePropertyOrientation);
if (val)
{
int orientation; // Note: This is an EXIF int for orientation, a number between 1 and 8
CFNumberGetValue(val, kCFNumberIntType, &orientation);
_imageOrientation = [NYXProgressiveImageView exifOrientationToiOSOrientation:orientation];
}
else
_imageOrientation = UIImageOrientationUp;
CFRelease(dic);
}
}
}
-(void)connectionDidFinishLoading:(__unused NSURLConnection*)connection
{
if (_dataTemp)
{
UIImage* img = [[UIImage alloc] initWithData:_dataTemp];
dispatch_sync(dispatch_get_main_queue(), ^{
if (_delegateFlags.delegateImageDownloadCompletedWithImage)
[_delegate imageDownloadCompletedWithImage:img];
self.image = img;
if (_delegateFlags.delegateImageDidLoadWithImage)
[_delegate imageDidLoadWithImage:img];
});
if (_caching)
{
// Create cache directory if it doesn't exist
BOOL isDir = YES;
NSFileManager* fileManager = [[NSFileManager alloc] init];
NSString* cacheDir = [NYXProgressiveImageView cacheDirectoryAddress];
if (![fileManager fileExistsAtPath:cacheDir isDirectory:&isDir])
[fileManager createDirectoryAtPath:cacheDir withIntermediateDirectories:NO attributes:nil error:nil];
NSString* path = [cacheDir stringByAppendingPathComponent:[self cachedImageSystemName]];
//[img saveToPath:path uti:CGImageSourceGetType(_imageSource) backgroundFillColor:nil];
[_dataTemp writeToFile:path options:NSDataWritingAtomic error:nil];
}
_dataTemp = nil;
}
if (_imageSource)
{
CFRelease(_imageSource);
_imageSource = NULL;
}
_connection = nil;
_url = nil;
_downloading = NO;
CFRunLoopStop(CFRunLoopGetCurrent());
}
-(void)connection:(__unused NSURLConnection*)connection didFailWithError:(__unused NSError*)error
{
if (_delegateFlags.delegateImageDownloadFailedWithData)
{
dispatch_sync(dispatch_get_main_queue(), ^{
[_delegate imageDownloadFailedWithData:_dataTemp];
});
}
_dataTemp = nil;
if (_imageSource)
{
CFRelease(_imageSource);
_imageSource = NULL;
}
_connection = nil;
_url = nil;
_downloading = NO;
CFRunLoopStop(CFRunLoopGetCurrent());
}
#pragma mark - Private
-(void)initializeAttributes
{
_cacheTime = kNyxDefaultCacheTimeValue;
_caching = NO;
_queue = dispatch_queue_create("com.cits.pdlqueue", DISPATCH_QUEUE_SERIAL);
_imageOrientation = UIImageOrientationUp;
_imageSource = NULL;
_dataTemp = nil;
}
-(CGImageRef)createTransitoryImage:(CGImageRef)partialImage
{
const size_t partialHeight = CGImageGetHeight(partialImage);
CGContextRef bmContext = NYXCreateARGBBitmapContext((size_t)_imageWidth, (size_t)_imageHeight, (size_t)_imageWidth * 4, NYXImageHasAlpha(partialImage));
if (!bmContext)
return NULL;
CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = _imageWidth, .size.height = partialHeight}, partialImage);
CGImageRef goodImageRef = CGBitmapContextCreateImage(bmContext);
CGContextRelease(bmContext);
return goodImageRef;
}
+(NSString*)cacheDirectoryAddress
{
NSArray* paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString* documentsDirectoryPath = [paths objectAtIndex:0];
return [documentsDirectoryPath stringByAppendingPathComponent:@"NYXProgressiveImageViewCache"];
}
-(NSString*)cachedImageSystemName
{
const char* concat_str = [[_url absoluteString] UTF8String];
if (!concat_str)
return @"";
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(concat_str, (CC_LONG)strlen(concat_str), result);
NSMutableString* hash = [[NSMutableString alloc] init];
for (unsigned int i = 0; i < CC_MD5_DIGEST_LENGTH; i++)
[hash appendFormat:@"%02X", result[i]];
return [hash lowercaseString];
}
-(void)resetCache
{
[[[NSFileManager alloc] init] removeItemAtPath:[[NYXProgressiveImageView cacheDirectoryAddress] stringByAppendingPathComponent:[self cachedImageSystemName]] error:nil];
}
+(UIImageOrientation)exifOrientationToiOSOrientation:(int)exifOrientation
{
UIImageOrientation orientation = UIImageOrientationUp;
switch (exifOrientation)
{
case 1:
orientation = UIImageOrientationUp;
break;
case 3:
orientation = UIImageOrientationDown;
break;
case 8:
orientation = UIImageOrientationLeft;
break;
case 6:
orientation = UIImageOrientationRight;
break;
case 2:
orientation = UIImageOrientationUpMirrored;
break;
case 4:
orientation = UIImageOrientationDownMirrored;
break;
case 5:
orientation = UIImageOrientationLeftMirrored;
break;
case 7:
orientation = UIImageOrientationRightMirrored;
break;
default:
break;
}
return orientation;
}
@end