forked from genkido/TWRDownloadManager
-
Notifications
You must be signed in to change notification settings - Fork 0
/
TWRDownloadManager.m
754 lines (644 loc) · 30.1 KB
/
TWRDownloadManager.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
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
//
// TWRDownloadManager.m
// DownloadManager
//
// Created by Michelangelo Chasseur on 25/07/14.
// Copyright (c) 2014 Touchware. All rights reserved.
//
#import "TWRDownloadManager.h"
#import "TWRDownloadObject.h"
#import <UIKit/UIKit.h>
static NSString* const EtagsDefault = @"ETagsDefault";
static NSTimeInterval const progressUpdateSeconds = 0.5;
@interface TWRDownloadManager () <NSURLSessionDelegate, NSURLSessionDownloadDelegate, NSURLSessionDataDelegate>
@property (strong, nonatomic) NSURLSession *session;
@property (strong, nonatomic) NSURLSession *backgroundSession;
@property (strong, nonatomic) NSMutableDictionary *downloads;
@property (strong, nonatomic) NSMutableDictionary *downloadOperations;
@property (atomic) NSTimeInterval timeLastProgressUpdate;
@property (strong, nonatomic) NSMutableDictionary* urlEtags;
@property (strong, nonatomic) NSOperationQueue* downloadQueue;
@end
@implementation TWRDownloadManager
+ (instancetype)sharedManager {
static id sharedManager = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedManager = [[self alloc] init];
});
return sharedManager;
}
- (instancetype)init {
self = [super init];
if (self) {
// Default session
NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration defaultSessionConfiguration];
self.session = [NSURLSession sessionWithConfiguration:configuration delegate:self delegateQueue:nil];
// Background session
NSURLSessionConfiguration *backgroundConfiguration = nil;
if (floor(NSFoundationVersionNumber) > NSFoundationVersionNumber_iOS_7_1) {
backgroundConfiguration = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:[[NSBundle mainBundle] bundleIdentifier]];
} else {
backgroundConfiguration = [NSURLSessionConfiguration backgroundSessionConfiguration:@"re.touchwa.downloadmanager"];
}
self.backgroundSession = [NSURLSession sessionWithConfiguration:backgroundConfiguration delegate:self delegateQueue:nil];
self.downloads = [NSMutableDictionary new];
self.downloadOperations = [NSMutableDictionary new];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
_urlEtags = [[defaults dictionaryForKey:EtagsDefault] mutableCopy];
if (!_urlEtags)
{
_urlEtags = [NSMutableDictionary dictionary];
}
_downloadQueue = [NSOperationQueue new];
[_downloadQueue setMaxConcurrentOperationCount:1];
}
return self;
}
#pragma mark - Downloading...
- (void)downloadFileForURL:(NSString *)urlString
withName:(NSString *)fileName
inDirectoryNamed:(NSString *)directory
friendlyName:(NSString *)friendlyName
progressBlock:(TWRDownloadProgressBlock)progressBlock
cancelBlock:(TWRDownloadCancelationBlock)cancelBlock
errorBlock:(TWRDownloadErrorBlock)errorBlock
remainingTime:(TWRDownloadRemainingTimeBlock)remainingTimeBlock
completionBlock:(TWRDownloadCompletionBlock)completionBlock
enableBackgroundMode:(BOOL)backgroundMode {
NSURL *url = [NSURL URLWithString:urlString];
if (!fileName) {
fileName = [urlString lastPathComponent];
}
if (!friendlyName) {
friendlyName = fileName;
}
if (![self fileDownloadCompletedForUrl:urlString]) {
NSLog(@"File is downloading!");
return;
}
TWRDownloadObject *dlObject = [[TWRDownloadObject alloc] initWithDownloadTask:nil progressBlock:progressBlock cancelBlock:cancelBlock errorBlock:errorBlock remainingTime:remainingTimeBlock completionBlock:completionBlock];
dlObject.isRedownload = NO;
[self.downloads setObject:dlObject forKey:urlString];
NSBlockOperation *operation = [NSBlockOperation new];
[operation addExecutionBlock:^{
NSUInteger bytes = 0;
if ([self fileExistsWithName:fileName inDirectory:directory]) {
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"HEAD"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest: request returningResponse: &response error: nil];
BOOL shouldDelete = YES;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *dictionary = [response allHeaderFields];
NSString* etag = [dictionary objectForKey:@"Etag"];
NSString* ranges = [dictionary objectForKey:@"Accept-Ranges"];
if (etag && [ranges isEqualToString:@"bytes"]) {
if ([[_urlEtags objectForKey:urlString] isEqualToString:etag])
{
shouldDelete = NO;
}
[_urlEtags setObject:etag forKey:urlString];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:_urlEtags forKey:EtagsDefault];
[defaults synchronize];
}
}
if (shouldDelete) {
[self deleteFileWithName:fileName inDirectory:directory];
}
else {
bytes = [[[NSFileManager defaultManager] attributesOfItemAtPath:[self localPathForFile:fileName inDirectory:directory] error:nil] fileSize];
}
}
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
if (bytes > 0) {
[request setValue:[NSString stringWithFormat:@"bytes=%ud-", bytes] forHTTPHeaderField:@"Range"];
}
if (_userAgent) {
[request setValue:_userAgent forHTTPHeaderField:@"User-Agent"];
}
NSURLSessionDataTask *downloadTask;
if (backgroundMode) {
downloadTask = [self.backgroundSession dataTaskWithRequest:request];
} else {
downloadTask = [self.session dataTaskWithRequest:request];
}
TWRDownloadObject *downloadObject = [[TWRDownloadObject alloc] initWithDownloadTask:downloadTask progressBlock:progressBlock cancelBlock:cancelBlock errorBlock:errorBlock remainingTime:remainingTimeBlock completionBlock:completionBlock];
downloadObject.startDate = [NSDate date];
downloadObject.fileName = fileName;
downloadObject.friendlyName = friendlyName;
downloadObject.directoryName = directory;
downloadObject.startBytes = bytes;
downloadObject.isRedownload = dlObject.isRedownload;
[self.downloads setObject:downloadObject forKey:urlString];
[downloadTask resume];
self.timeLastProgressUpdate = 0;
}];
[self.downloadOperations addEntriesFromDictionary:@{urlString:operation}];
[_downloadQueue addOperation:operation];
}
- (void)downloadFileForURL:(NSString *)urlString
withName:(NSString *)fileName
inDirectoryNamed:(NSString *)directory
progressBlock:(TWRDownloadProgressBlock)progressBlock
remainingTime:(TWRDownloadRemainingTimeBlock)remainingTimeBlock
completionBlock:(TWRDownloadCompletionBlock)completionBlock
enableBackgroundMode:(BOOL)backgroundMode {
[self downloadFileForURL:urlString
withName:fileName
inDirectoryNamed:directory
friendlyName:fileName
progressBlock:progressBlock
cancelBlock:nil
errorBlock:nil
remainingTime:remainingTimeBlock
completionBlock:completionBlock
enableBackgroundMode:backgroundMode];
}
- (void)downloadFileForURL:(NSString *)url
inDirectoryNamed:(NSString *)directory
progressBlock:(TWRDownloadProgressBlock)progressBlock
remainingTime:(TWRDownloadRemainingTimeBlock)remainingTimeBlock
completionBlock:(TWRDownloadCompletionBlock)completionBlock
enableBackgroundMode:(BOOL)backgroundMode {
[self downloadFileForURL:url
withName:[url lastPathComponent]
inDirectoryNamed:directory
progressBlock:progressBlock
remainingTime:remainingTimeBlock
completionBlock:completionBlock
enableBackgroundMode:backgroundMode];
}
- (void)downloadFileForURL:(NSString *)url
progressBlock:(TWRDownloadProgressBlock)progressBlock
remainingTime:(TWRDownloadRemainingTimeBlock)remainingTimeBlock
completionBlock:(TWRDownloadCompletionBlock)completionBlock
enableBackgroundMode:(BOOL)backgroundMode {
[self downloadFileForURL:url
withName:[url lastPathComponent]
inDirectoryNamed:nil
progressBlock:progressBlock
remainingTime:remainingTimeBlock
completionBlock:completionBlock
enableBackgroundMode:backgroundMode];
}
- (void)downloadFileForURL:(NSString *)urlString
withName:(NSString *)fileName
inDirectoryNamed:(NSString *)directory
progressBlock:(TWRDownloadProgressBlock)progressBlock
completionBlock:(TWRDownloadCompletionBlock)completionBlock
enableBackgroundMode:(BOOL)backgroundMode {
[self downloadFileForURL:urlString
withName:fileName
inDirectoryNamed:directory
progressBlock:progressBlock
remainingTime:nil
completionBlock:completionBlock
enableBackgroundMode:backgroundMode];
}
- (void)downloadFileForURL:(NSString *)urlString
inDirectoryNamed:(NSString *)directory
progressBlock:(TWRDownloadProgressBlock)progressBlock
completionBlock:(TWRDownloadCompletionBlock)completionBlock
enableBackgroundMode:(BOOL)backgroundMode {
// if no file name was provided, use the last path component of the URL as its name
[self downloadFileForURL:urlString
withName:[urlString lastPathComponent]
inDirectoryNamed:directory
progressBlock:progressBlock
completionBlock:completionBlock
enableBackgroundMode:backgroundMode];
}
- (void)downloadFileForURL:(NSString *)urlString
progressBlock:(TWRDownloadProgressBlock)progressBlock
completionBlock:(TWRDownloadCompletionBlock)completionBlock
enableBackgroundMode:(BOOL)backgroundMode {
[self downloadFileForURL:urlString
inDirectoryNamed:nil
progressBlock:progressBlock
completionBlock:completionBlock
enableBackgroundMode:backgroundMode];
}
- (void)cancelDownloadForUrl:(NSString *)fileIdentifier {
NSOperation* op = [self.downloadOperations objectForKey:fileIdentifier];
[op cancel];
TWRDownloadObject *download = [self.downloads objectForKey:fileIdentifier];
if (download) {
NSString *url = download.downloadTask.originalRequest.URL.absoluteString;
[download.downloadTask cancel];
[self.downloads removeObjectForKey:fileIdentifier];
if (download.cancelationBlock) {
download.cancelationBlock(url);
}
}
if (self.downloads.count == 0) {
[self cleanTmpDirectory];
}
}
- (void)cancelAllDownloads {
[_downloadQueue cancelAllOperations];
[self.downloads enumerateKeysAndObjectsUsingBlock:^(id key, TWRDownloadObject *download, BOOL *stop) {
NSString *url = download.downloadTask.originalRequest.URL.absoluteString;
[download.downloadTask cancel];
[self.downloads removeObjectForKey:key];
if (download.cancelationBlock) {
download.cancelationBlock(url);
}
}];
[self cleanTmpDirectory];
}
- (NSArray *)currentDownloads {
NSMutableArray *currentDownloads = [NSMutableArray new];
[self.downloads enumerateKeysAndObjectsUsingBlock:^(id key, TWRDownloadObject *download, BOOL *stop) {
[currentDownloads addObject:download.downloadTask.originalRequest.URL.absoluteString];
}];
return currentDownloads;
}
#pragma mark - NSURLSession Delegate
//- (void)URLSession:(NSURLSession *)session
// downloadTask:(NSURLSessionDownloadTask *)downloadTask
// didWriteData:(int64_t)bytesWritten
// totalBytesWritten:(int64_t)totalBytesWritten
//totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
// NSString *fileIdentifier = downloadTask.originalRequest.URL.absoluteString;
// TWRDownloadObject *download = [self.downloads objectForKey:fileIdentifier];
// if (download.progressBlock) {
// CGFloat progress = (CGFloat)totalBytesWritten / (CGFloat)totalBytesExpectedToWrite;
// dispatch_async(dispatch_get_main_queue(), ^(void) {
// if(download.progressBlock){
// download.progressBlock(fileIdentifier, progress); //exception when progressblock is nil
// }
// });
// }
//
// CGFloat remainingTime = [self remainingTimeForDownload:download bytesTransferred:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
// if (download.remainingTimeBlock) {
// dispatch_async(dispatch_get_main_queue(), ^(void) {
// if (download.remainingTimeBlock) {
// download.remainingTimeBlock(fileIdentifier, (NSUInteger)remainingTime);
// }
// });
// }
//}
-(void)URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)r completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
{
NSHTTPURLResponse *response = (NSHTTPURLResponse*)r;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *dictionary = [response allHeaderFields];
NSString* etag = [dictionary objectForKey:@"Etag"];
if (etag)
{
[_urlEtags setObject:etag forKey:dataTask.originalRequest.URL.absoluteString];
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:_urlEtags forKey:EtagsDefault];
[defaults synchronize];
}
}
completionHandler(NSURLSessionResponseAllow);
}
// Download progress
- (void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask didReceiveData:(nonnull NSData *)data
{
NSString *fileIdentifier = dataTask.originalRequest.URL.absoluteString;
TWRDownloadObject *download = [self.downloads objectForKey:fileIdentifier];
NSError *error;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:[self localPathForFile:download.fileName inDirectory:download.directoryName] error:&error];
long long totalBytesWritten = 0;
if (!error)
{
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
totalBytesWritten = [fileSizeNumber longLongValue];
}
totalBytesWritten += [data length];
long long totalBytesExpectedToWrite = dataTask.response.expectedContentLength;
totalBytesExpectedToWrite = totalBytesExpectedToWrite <= 0 ? -1 : totalBytesExpectedToWrite + download.startBytes;
NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:[self localPathForFile:download.fileName inDirectory:download.directoryName]];
if (!fileHandle)
{
[data writeToFile:[self localPathForFile:download.fileName inDirectory:download.directoryName] atomically:YES];
}
else
{
@try {
[fileHandle seekToEndOfFile];
[fileHandle writeData:data];
[fileHandle closeFile];
}
@catch (NSException *exception) {
if (fileIdentifier) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
[self cancelDownloadForUrl:fileIdentifier];
if (download.errorBlock) {
download.errorBlock(fileIdentifier);
}
});
}
}
}
NSTimeInterval now = [[NSDate date] timeIntervalSince1970];
if (now - self.timeLastProgressUpdate > progressUpdateSeconds)
{
self.timeLastProgressUpdate = now;
if (download.progressBlock) {
CGFloat progress = (CGFloat)totalBytesWritten / (CGFloat)totalBytesExpectedToWrite;
dispatch_async(dispatch_get_main_queue(), ^(void) {
if(download.progressBlock){
download.progressBlock(fileIdentifier, progress); //exception when progressblock is nil
}
});
}
CGFloat remainingTime = [self remainingTimeForDownload:download bytesTransferred:totalBytesWritten totalBytesExpectedToWrite:totalBytesExpectedToWrite];
if (download.remainingTimeBlock) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
if (download.remainingTimeBlock) {
download.remainingTimeBlock(fileIdentifier, (NSUInteger)remainingTime);
}
});
}
}
}
//// Download finished
//- (void)URLSession:(NSURLSession *)session dataTask:(nonnull NSURLSessionDataTask *)dataTask willCacheResponse:(nonnull NSCachedURLResponse *)proposedResponse completionHandler:(nonnull void (^)(NSCachedURLResponse * _Nullable))completionHandler
//{
//
//}
//- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
//// NSLog(@"Download finisehd!");
//
// NSError *error;
// NSURL *destinationLocation;
//
// NSString *fileIdentifier = downloadTask.originalRequest.URL.absoluteString;
// TWRDownloadObject *download = [self.downloads objectForKey:fileIdentifier];
//
// BOOL success = YES;
//
// if ([downloadTask.response isKindOfClass:[NSHTTPURLResponse class]]) {
// NSInteger statusCode = [(NSHTTPURLResponse*)downloadTask.response statusCode];
// if (statusCode >= 400) {
// NSLog(@"ERROR: HTTP status code %@", @(statusCode));
// success = NO;
// }
// }
//
// if (success) {
// if (download.directoryName) {
// destinationLocation = [[[self cachesDirectoryUrlPath] URLByAppendingPathComponent:download.directoryName] URLByAppendingPathComponent:download.fileName];
// } else {
// destinationLocation = [[self cachesDirectoryUrlPath] URLByAppendingPathComponent:download.fileName];
// }
//
// // Move downloaded item from tmp directory to te caches directory
// // (not synced with user's iCloud documents)
// [[NSFileManager defaultManager] moveItemAtURL:location
// toURL:destinationLocation
// error:&error];
// if (error) {
// NSLog(@"ERROR: %@", error);
// }
//
// if (download.completionBlock) {
// dispatch_async(dispatch_get_main_queue(), ^(void) {
// download.completionBlock(fileIdentifier);
// });
// }
//
// dispatch_async(dispatch_get_main_queue(), ^{
// // Show a local notification when download is over.
// UILocalNotification *localNotification = [[UILocalNotification alloc] init];
// localNotification.alertBody = [NSString stringWithFormat:@"%@ has been downloaded", download.friendlyName];
// [[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
// });
// }
// else {
// if (download.errorBlock) {
// dispatch_async(dispatch_get_main_queue(), ^(void) {
// download.errorBlock(fileIdentifier);
// });
// }
// }
//
// // remove object from the download
// [self.downloads removeObjectForKey:fileIdentifier];
//}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
NSString *fileIdentifier = task.originalRequest.URL.absoluteString;
TWRDownloadObject *download = [self.downloads objectForKey:fileIdentifier];
BOOL success = YES;
if ([task.response isKindOfClass:[NSHTTPURLResponse class]]) {
NSInteger statusCode = [(NSHTTPURLResponse*)task.response statusCode];
if (statusCode >= 400) {
NSLog(@"ERROR: HTTP status code %@", @(statusCode));
success = NO;
}
}
if (error || !success) {
NSLog(@"ERROR: %@", error);
if (!success) {
if ([self fileExistsWithName:download.fileName] && !download.isRedownload) {
NSString *path = [download.fileName stringByAppendingString:@"_tmp"];
if (path) {
[self.downloads removeObjectForKey:fileIdentifier];
[self.urlEtags removeObjectForKey:fileIdentifier];
[self deleteFileWithName:path];
[self downloadFileForURL:fileIdentifier withName:path inDirectoryNamed:download.directoryName friendlyName:download.friendlyName progressBlock:download.progressBlock cancelBlock:download.cancelationBlock errorBlock:^(NSString *url) {
// Download failed- delete both files for good measure
[self deleteFileWithName:download.fileName];
[self deleteFileWithName:path];
if (download.errorBlock) {
download.errorBlock(url);
}
} remainingTime:download.remainingTimeBlock completionBlock:^(NSString *url) {
// Delete file in original path
[self deleteFileWithName:download.fileName];
NSError *error = nil;
[[NSFileManager defaultManager] moveItemAtPath:path toPath:download.fileName error:&error];
download.completionBlock(url);
} enableBackgroundMode:YES];
TWRDownloadObject *redownload = [self.downloads objectForKey:fileIdentifier];
redownload.isRedownload = YES;
return;
}
}
}
if (download.errorBlock) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
download.errorBlock(fileIdentifier);
});
}
}
else
{
if (fileIdentifier) {
[_urlEtags removeObjectForKey:fileIdentifier];
}
NSUserDefaults* defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:_urlEtags forKey:EtagsDefault];
[defaults synchronize];
if (download.completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
download.completionBlock(fileIdentifier);
});
}
}
// remove object from the download
if (fileIdentifier) {
[self.downloads removeObjectForKey:fileIdentifier];
}
}
- (CGFloat)remainingTimeForDownload:(TWRDownloadObject *)download
bytesTransferred:(int64_t)bytesTransferred
totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:download.startDate];
CGFloat speed = (CGFloat)bytesTransferred / (CGFloat)timeInterval;
CGFloat remainingBytes = totalBytesExpectedToWrite - bytesTransferred;
CGFloat remainingTime = remainingBytes / speed;
return remainingTime;
}
#pragma mark - File Management
- (BOOL)createDirectoryNamed:(NSString *)directory {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [paths objectAtIndex:0];
NSString *targetDirectory = [cachesDirectory stringByAppendingPathComponent:directory];
NSError *error;
return [[NSFileManager defaultManager] createDirectoryAtPath:targetDirectory
withIntermediateDirectories:YES
attributes:nil
error:&error];
}
- (NSURL *)cachesDirectoryUrlPath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [paths objectAtIndex:0];
NSURL *cachesDirectoryUrl = [NSURL fileURLWithPath:cachesDirectory];
return cachesDirectoryUrl;
}
- (BOOL)fileDownloadCompletedForUrl:(NSString *)fileIdentifier {
BOOL retValue = YES;
TWRDownloadObject *download = [self.downloads objectForKey:fileIdentifier];
if (download) {
// downloads are removed once they finish
retValue = NO;
}
return retValue;
}
- (BOOL)isFileDownloadingForUrl:(NSString *)fileIdentifier {
return [self isFileDownloadingForUrl:fileIdentifier
withProgressBlock:nil];
}
- (BOOL)isFileDownloadingForUrl:(NSString *)fileIdentifier
withProgressBlock:(TWRDownloadProgressBlock)block {
return [self isFileDownloadingForUrl:fileIdentifier
withProgressBlock:block
completionBlock:nil];
}
- (BOOL)isFileDownloadingForUrl:(NSString *)fileIdentifier
withProgressBlock:(TWRDownloadProgressBlock)block
completionBlock:(TWRDownloadCompletionBlock)completionBlock {
BOOL retValue = NO;
TWRDownloadObject *download = [self.downloads objectForKey:fileIdentifier];
if (download) {
if (block) {
download.progressBlock = block;
}
if (completionBlock) {
download.completionBlock = completionBlock;
}
retValue = YES;
}
return retValue;
}
#pragma mark File existance
- (NSString *)localPathForFile:(NSString *)fileIdentifier {
return [self localPathForFile:fileIdentifier inDirectory:nil];
}
- (NSString *)localPathForFile:(NSString *)fileIdentifier inDirectory:(NSString *)directoryName {
NSString *fileName = [fileIdentifier lastPathComponent];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [paths objectAtIndex:0];
return [[cachesDirectory stringByAppendingPathComponent:directoryName] stringByAppendingPathComponent:fileName];
}
- (BOOL)fileExistsForUrl:(NSString *)urlString {
return [self fileExistsForUrl:urlString inDirectory:nil];
}
- (BOOL)fileExistsForUrl:(NSString *)urlString inDirectory:(NSString *)directoryName {
return [self fileExistsWithName:[urlString lastPathComponent] inDirectory:directoryName];
}
- (BOOL)fileExistsWithName:(NSString *)fileName
inDirectory:(NSString *)directoryName {
BOOL exists = NO;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [paths objectAtIndex:0];
// if no directory was provided, we look by default in the base cached dir
if ([[NSFileManager defaultManager] fileExistsAtPath:[[cachesDirectory stringByAppendingPathComponent:directoryName] stringByAppendingPathComponent:fileName]]) {
exists = YES;
}
return exists;
}
- (BOOL)fileExistsWithName:(NSString *)fileName {
return [self fileExistsWithName:fileName inDirectory:nil];
}
#pragma mark File deletion
- (BOOL)deleteFileForUrl:(NSString *)urlString {
return [self deleteFileForUrl:urlString inDirectory:nil];
}
- (BOOL)deleteFileForUrl:(NSString *)urlString inDirectory:(NSString *)directoryName {
return [self deleteFileWithName:[urlString lastPathComponent] inDirectory:directoryName];
}
- (BOOL)deleteFileWithName:(NSString *)fileName {
return [self deleteFileWithName:fileName inDirectory:nil];
}
- (BOOL)deleteFileWithName:(NSString *)fileName
inDirectory:(NSString *)directoryName {
BOOL deleted = NO;
NSError *error;
NSURL *fileLocation;
if (directoryName) {
fileLocation = [[[self cachesDirectoryUrlPath] URLByAppendingPathComponent:directoryName] URLByAppendingPathComponent:fileName];
} else {
fileLocation = [[self cachesDirectoryUrlPath] URLByAppendingPathComponent:fileName];
}
// Move downloaded item from tmp directory to te caches directory
// (not synced with user's iCloud documents)
[[NSFileManager defaultManager] removeItemAtURL:fileLocation error:&error];
if (error) {
deleted = NO;
NSLog(@"Error deleting file: %@", error);
} else {
deleted = YES;
}
return deleted;
}
#pragma mark - Clean directory
- (void)cleanDirectoryNamed:(NSString *)directory {
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:directory error:&error]) {
[fm removeItemAtPath:[directory stringByAppendingPathComponent:file] error:&error];
}
}
- (void)cleanTmpDirectory {
NSArray* tmpDirectory = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:NSTemporaryDirectory() error:NULL];
for (NSString *file in tmpDirectory) {
[[NSFileManager defaultManager] removeItemAtPath:[NSString stringWithFormat:@"%@%@", NSTemporaryDirectory(), file] error:NULL];
}
}
#pragma mark - Background download
- (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
// Check if all download tasks have been finished.
[session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
if ([dataTasks count] == 0) {
if (self.backgroundTransferCompletionHandler != nil) {
// Copy locally the completion handler.
void(^completionHandler)() = self.backgroundTransferCompletionHandler;
[[NSOperationQueue mainQueue] addOperationWithBlock:^{
// Call the completion handler to tell the system that there are no other background transfers.
completionHandler();
}];
// Make nil the backgroundTransferCompletionHandler.
self.backgroundTransferCompletionHandler = nil;
}
}
}];
}
@end