-
Notifications
You must be signed in to change notification settings - Fork 1
/
TCWebImageView.m
321 lines (241 loc) · 9.46 KB
/
TCWebImageView.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
//
// TCImageView.m
// TCImageViewDemo
//
#import "TCWebImageView.h"
#import <CommonCrypto/CommonDigest.h>
@interface TCWebImageView ()
@property long long expectedFileSize;
@property long long previousDataLengthReading;
@property NSURLConnection *connection;
@property NSMutableData *data;
- (void)setDefaults;
@end
@implementation TCWebImageView
- (id)init
{
self = [super init];
if (self)
{
[self setDefaults];
}
return self;
}
- (id)initWithURL:(NSURL *)url placeholderImage:(UIImage *)image
{
UIImageView *placeholderView = [[UIImageView alloc] initWithImage:image];
return [self initWithURL:url placeholderView:placeholderView];
}
- (id)initWithURL:(NSURL *)url placeholderView:(UIView *)placeholderView
{
self = [super init];
if (self)
{
[self setDefaults];
if (!url) {
NSLog(@"*** TCWebImageView Warning: NSURL was not provided correctly, if you have urls with spaces try [stringURL stringByAddingPercentEscapesUsingEncoding:NSASCIIStringEncoding]");
}
self.url = url;
if (placeholderView != nil)
{
self.placeholder = placeholderView;
self.placeholder.alpha = 1.0;
[self addSubview:self.placeholder];
}
}
return self;
}
- (id)initWithURL:(NSURL *)url placeholderImage:(UIImage *)image completed:(TCWebImageViewFinishedLoading)complete failed:(TCWebImageViewDidFailLoading)failed loadingProcess:(TCWebImageViewLoadingProcess)loading
{
self.finishedLoadingBlock = complete;
self.failedLoadingBlock = failed;
self.loadingProcessBlock = loading;
return [self initWithURL:url placeholderImage:image];
}
-(void)setFrame:(CGRect)frame
{
[super setFrame:frame];
self.placeholder.frame = self.bounds;
}
-(void)setContentMode:(UIViewContentMode)contentMode
{
[super setContentMode:contentMode];
[self.placeholder setContentMode:contentMode];
}
- (void)setDefaults
{
self.caching = NO;
self.cacheTime = (double)604800; // 7 days
self.delegate = nil;
}
- (void)loadImage
{
if (self.caching){
NSFileManager *fileManager = [NSFileManager defaultManager];
if ([fileManager fileExistsAtPath:[[TCWebImageView cacheDirectoryAddress] stringByAppendingPathComponent:[self cachedImageSystemName]]])
{
NSDate *mofificationDate = [[fileManager attributesOfItemAtPath:[[TCWebImageView cacheDirectoryAddress] stringByAppendingPathComponent:[self cachedImageSystemName]] error:nil] objectForKey:NSFileModificationDate];
if ([mofificationDate timeIntervalSinceNow] > self.cacheTime) {
// Removes old cache file...
[self resetCache];
} else {
// Loads image from cache without networking
NSData *localImageData = [NSData dataWithContentsOfFile:[[TCWebImageView cacheDirectoryAddress] stringByAppendingPathComponent:[self cachedImageSystemName]]];
UIImage *localImage = [UIImage imageWithData:localImageData];
if ([self.delegate respondsToSelector:@selector(webImageView:willUpdateImage:)]) {
[self.delegate webImageView:self willUpdateImage:localImage];
}
self.image = localImage;
if (self.placeholder)
{
if (self.placeholder.frame.size.width == 0.0 || self.placeholder.frame.size.height == 0.0) {
self.placeholder.frame = self.frame;
}
[self.placeholder setAlpha:0];
}
if ([self.delegate respondsToSelector:@selector(webImageView:didFinishLoadingImage:fromCache:)]) {
[self.delegate webImageView:self didFinishLoadingImage:localImage fromCache:YES];
}
if (self.finishedLoadingBlock) {
self.finishedLoadingBlock(localImage,YES);
}
return;
}
}
}
// Loads image from network if no "return;" is triggered (no cache file found)
self.expectedFileSize = 0;
NSURLRequest *request = [NSURLRequest requestWithURL:self.url cachePolicy:NSURLRequestReturnCacheDataElseLoad timeoutInterval:30.0];
self.connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
}
-(void)cancelLoad {
if (self.connection) {
[self.connection cancel];
self.expectedFileSize = 0;
self.data = nil;
self.connection = nil;
}
}
- (void)reloadWithURL:(NSURL *)url;
{
[self cancelLoad];
self.image = nil;
if (self.placeholder) {
self.placeholder.alpha = 1.0;
}
self.url = url;
[self loadImage];
}
#pragma -
#pragma Networking Delegates
-(void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
if (self.delegate && [self.delegate respondsToSelector:@selector(webImageView:failedWithError:)]) {
[self.delegate webImageView:self failedWithError:error];
}
if (self.failedLoadingBlock) {
self.failedLoadingBlock(error);
}
self.expectedFileSize = 0;
self.data = nil;
[self.connection cancel];
self.connection = nil;
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
self.expectedFileSize = [response expectedContentLength];
}
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)incrementalData
{
// NSLog(@"didReceiveData");
if (self.data == nil)
self.data = [[NSMutableData alloc] initWithCapacity:2048];
if (self.data.length - self.previousDataLengthReading > DOWNLOAD_PROGRESS_INCREMENT_KB * 1024) {
if ([self.delegate respondsToSelector:@selector(webImageView:loadedBytes:totalBytes:)]) {
[self.delegate webImageView:self loadedBytes:(long long)self.data.length totalBytes:self.expectedFileSize];
}
if (self.loadingProcessBlock) {
self.loadingProcessBlock(self.expectedFileSize,(long long)self.data.length);
}
_loadingProgress = [NSNumber numberWithFloat:(double)self.data.length / (double)self.expectedFileSize];
self.previousDataLengthReading = self.data.length;
}
[self.data appendData:incrementalData];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)theConnection
{
//NSLog(@"connectionDidFinishLoading");
NSFileManager *fileManager = [NSFileManager defaultManager];
UIImage *imageData = [UIImage imageWithData:self.data];
if ([self.delegate respondsToSelector:@selector(webImageView:willUpdateImage:)]) {
[self.delegate webImageView:self willUpdateImage:imageData];
}
self.image = imageData;
if (self.placeholder)
{
[self.placeholder setAlpha:0];
}
if (self.caching)
{
// Create Cache directory if it doesn't exist
BOOL isDir = YES;
if (![fileManager fileExistsAtPath:[TCWebImageView cacheDirectoryAddress] isDirectory:&isDir]) {
[fileManager createDirectoryAtPath:[TCWebImageView cacheDirectoryAddress] withIntermediateDirectories:NO attributes:nil error:nil];
}
// Write image cache file
NSError *error;
NSData *cachedImage = UIImageJPEGRepresentation(self.image, CACHED_IMAGE_JPEG_QUALITY);
@try {
[cachedImage writeToFile:[[TCWebImageView cacheDirectoryAddress] stringByAppendingPathComponent:[self cachedImageSystemName]] options:NSDataWritingAtomic error:&error];
}
@catch (NSException * e) {
if ([self.delegate respondsToSelector:@selector(webImageView:failedWithError:)]) {
NSError *error = [NSError errorWithDomain:@"No image fount in cache" code:001 userInfo:nil];
[self.delegate webImageView:self failedWithError:error];
}
if (self.failedLoadingBlock) {
self.failedLoadingBlock(error);
}
}
}
self.data = nil;
[self.connection cancel];
self.connection = nil;
if ([self.delegate respondsToSelector:@selector(webImageView:didFinishLoadingImage:fromCache:)]) {
[self.delegate webImageView:self didFinishLoadingImage:imageData fromCache:NO];
}
if (self.finishedLoadingBlock) {
self.finishedLoadingBlock(imageData,NO);
}
}
#pragma mark -
#pragma mark Caching Methods
+ (void)resetGlobalCache
{
NSError *error;
[[NSFileManager defaultManager] removeItemAtPath:[TCWebImageView cacheDirectoryAddress] error:&error];
}
+ (NSString*)cacheDirectoryAddress
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
return [documentsDirectoryPath stringByAppendingPathComponent:@"TCWebImageView-Cache"];
}
- (void)resetCache
{
NSError *error;
[[NSFileManager defaultManager] removeItemAtPath:[[TCWebImageView cacheDirectoryAddress] stringByAppendingPathComponent:[self cachedImageSystemName]] error:&error];
}
- (NSString*)cachedImageSystemName
{
const char *concat_str = [[self.url absoluteString] UTF8String];
if (concat_str == nil)
{
return @"";
}
unsigned char result[CC_MD5_DIGEST_LENGTH];
CC_MD5(concat_str, strlen(concat_str), result);
NSMutableString *hash = [NSMutableString string];
for (int i = 0; i < 16; i++)
[hash appendFormat:@"%02X", result[i]];
return [[hash lowercaseString] stringByAppendingPathExtension:@"jpeg"];
}
@end