/
DTLazyImageView.m
320 lines (254 loc) · 7.84 KB
/
DTLazyImageView.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
//
// DTLazyImageView.m
// DTCoreText
//
// Created by Oliver Drobnik on 5/20/11.
// Copyright 2011 Drobnik.com. All rights reserved.
//
#import <ImageIO/ImageIO.h>
#import "DTLazyImageView.h"
#import "DTLog.h"
static NSCache *_imageCache = nil;
NSString * const DTLazyImageViewWillStartDownloadNotification = @"DTLazyImageViewWillStartDownloadNotification";
NSString * const DTLazyImageViewDidFinishDownloadNotification = @"DTLazyImageViewDidFinishDownloadNotification";
@interface DTLazyImageView ()
- (void)_notifyDelegate;
@end
@implementation DTLazyImageView
{
NSURL *_url;
NSMutableURLRequest *_urlRequest;
NSURLConnection *_connection;
NSMutableData *_receivedData;
/* For progressive download */
CGImageSourceRef _imageSource;
CGFloat _fullHeight;
CGFloat _fullWidth;
NSUInteger _expectedSize;
BOOL shouldShowProgressiveDownload;
DT_WEAK_VARIABLE id<DTLazyImageViewDelegate> _delegate;
}
- (void)dealloc
{
_delegate = nil; // to avoid late notification
[_connection cancel];
if (_imageSource) CFRelease(_imageSource);
}
- (void)loadImageAtURL:(NSURL *)url
{
// local files we don't need to get asynchronously
if ([url isFileURL] || [url.scheme isEqualToString:@"data"])
{
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
NSData *data = [NSData dataWithContentsOfURL:url];
dispatch_async(dispatch_get_main_queue(), ^{
[self completeDownloadWithData:data];
});
});
return;
}
@autoreleasepool
{
if (!_urlRequest)
{
_urlRequest = [[NSMutableURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:10.0];
}
else
{
[_urlRequest setCachePolicy:NSURLRequestReturnCacheDataElseLoad];
[_urlRequest setTimeoutInterval:10.0];
}
_connection = [[NSURLConnection alloc] initWithRequest:_urlRequest delegate:self startImmediately:NO];
[_connection scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
[[NSNotificationCenter defaultCenter] postNotificationName:DTLazyImageViewWillStartDownloadNotification object:self];
[_connection start];
}
}
- (void)didMoveToSuperview
{
[super didMoveToSuperview];
if (!self.image && (_url || _urlRequest) && !_connection && self.superview)
{
UIImage *image = [_imageCache objectForKey:_url];
if (image)
{
self.image = image;
_fullWidth = image.size.width;
_fullHeight = image.size.height;
// this has to be synchronous
[self _notifyDelegate];
return;
}
[self loadImageAtURL:_url];
}
}
- (void)cancelLoading
{
[_connection cancel];
_connection = nil;
_receivedData = nil;
}
#pragma mark Progressive Image
-(CGImageRef)newTransitoryImage:(CGImageRef)partialImg
{
const size_t height = CGImageGetHeight(partialImg);
CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB();
size_t lFullWidth = (size_t)ceil(_fullWidth);
size_t lFullHeight = (size_t)ceil(_fullHeight);
CGContextRef bmContext = CGBitmapContextCreate(NULL, lFullWidth, lFullHeight, 8, lFullWidth * 4, colorSpace, kCGBitmapByteOrderDefault | kCGImageAlphaPremultipliedFirst);
CGColorSpaceRelease(colorSpace);
if (!bmContext)
{
// fail creating context
return NULL;
}
CGContextDrawImage(bmContext, (CGRect){.origin.x = 0.0f, .origin.y = 0.0f, .size.width = _fullWidth, .size.height = height}, partialImg);
CGImageRef goodImageRef = CGBitmapContextCreateImage(bmContext);
CGContextRelease(bmContext);
return goodImageRef;
}
- (void)createAndShowProgressiveImage
{
if (!_imageSource)
{
return;
}
/* For progressive download */
const NSUInteger totalSize = [_receivedData length];
CGImageSourceUpdateData(_imageSource, (__bridge CFDataRef)_receivedData, (totalSize == _expectedSize) ? true : false);
if (_fullHeight > 0 && _fullWidth > 0)
{
CGImageRef image = CGImageSourceCreateImageAtIndex(_imageSource, 0, NULL);
if (image)
{
CGImageRef imgTmp = [self newTransitoryImage:image]; // iOS fix to correctly handle JPG see : http://www.cocoabyss.com/mac-os-x/progressive-image-download-imageio/
if (imgTmp)
{
UIImage *uimage = [[UIImage alloc] initWithCGImage:imgTmp];
CGImageRelease(imgTmp);
dispatch_async(dispatch_get_main_queue(), ^{ self.image = uimage; } );
}
CGImageRelease(image);
}
}
else
{
CFDictionaryRef properties = CGImageSourceCopyPropertiesAtIndex(_imageSource, 0, NULL);
if (properties)
{
CFTypeRef val = CFDictionaryGetValue(properties, kCGImagePropertyPixelHeight);
if (val)
CFNumberGetValue(val, kCFNumberFloatType, &_fullHeight);
val = CFDictionaryGetValue(properties, kCGImagePropertyPixelWidth);
if (val)
CFNumberGetValue(val, kCFNumberFloatType, &_fullWidth);
CFRelease(properties);
}
}
}
#pragma mark NSURL Loading
- (void)_notifyDelegate
{
if ([self.delegate respondsToSelector:@selector(lazyImageView:didChangeImageSize:)]) {
[self.delegate lazyImageView:self didChangeImageSize:CGSizeMake(_fullWidth, _fullHeight)];
}
}
- (void)completeDownloadWithData:(NSData *)data
{
UIImage *image = [[UIImage alloc] initWithData:data];
self.image = image;
_fullWidth = image.size.width;
_fullHeight = image.size.height;
[self _notifyDelegate];
static dispatch_once_t predicate;
dispatch_once(&predicate, ^{
_imageCache = [[NSCache alloc] init];
});
if (_url)
{
if (image)
{
// cache image
[_imageCache setObject:image forKey:_url];
}
else
{
DTLogWarning(@"Warning, %@ did not get an image for %@", NSStringFromClass([self class]), [_url absoluteString]);
}
}
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// every time we get an response it might be a forward, so we discard what data we have
_receivedData = nil;
// does not fire for local file URLs
if ([response isKindOfClass:[NSHTTPURLResponse class]])
{
NSHTTPURLResponse *httpResponse = (id)response;
if (![[httpResponse MIMEType] hasPrefix:@"image"])
{
[self cancelLoading];
return;
}
}
/* For progressive download */
_fullWidth = _fullHeight = -1.0f;
_expectedSize = (NSUInteger)[response expectedContentLength];
_receivedData = [[NSMutableData alloc] init];
}
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
[_receivedData appendData:data];
if (!CGImageSourceCreateIncremental || !shouldShowProgressiveDownload)
{
// don't show progressive
return;
}
if (!_imageSource)
{
_imageSource = CGImageSourceCreateIncremental(NULL);
}
[self createAndShowProgressiveImage];
}
- (void)removeFromSuperview
{
[super removeFromSuperview];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
if (_receivedData)
{
[self performSelectorOnMainThread:@selector(completeDownloadWithData:) withObject:_receivedData waitUntilDone:YES];
_receivedData = nil;
}
_connection = nil;
/* For progressive download */
if (_imageSource)
CFRelease(_imageSource), _imageSource = NULL;
CFRunLoopStop(CFRunLoopGetCurrent());
// success = no userInfo
[[NSNotificationCenter defaultCenter] postNotificationName:DTLazyImageViewDidFinishDownloadNotification object:self];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
_connection = nil;
_receivedData = nil;
/* For progressive download */
if (_imageSource)
CFRelease(_imageSource), _imageSource = NULL;
CFRunLoopStop(CFRunLoopGetCurrent());
// send completion notification, pack in error as well
NSDictionary *userInfo = [NSDictionary dictionaryWithObject:error forKey:@"Error"];
[[NSNotificationCenter defaultCenter] postNotificationName:DTLazyImageViewDidFinishDownloadNotification object:self userInfo:userInfo];
}
#pragma mark Properties
- (void) setUrlRequest:(NSMutableURLRequest *)request
{
_urlRequest = request;
self.url = [_urlRequest URL];
}
@synthesize delegate=_delegate;
@synthesize shouldShowProgressiveDownload;
@synthesize url = _url;
@synthesize urlRequest = _urlRequest;
@end