-
Notifications
You must be signed in to change notification settings - Fork 99
/
TWRDownloadManager.m
502 lines (422 loc) · 19.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
//
// 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>
@interface TWRDownloadManager () <NSURLSessionDelegate, NSURLSessionDownloadDelegate>
@property (strong, nonatomic) NSURLSession *session;
@property (strong, nonatomic) NSURLSession *backgroundSession;
@property (strong, nonatomic) NSMutableDictionary *downloads;
@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];
}
return self;
}
#pragma mark - Downloading...
- (void)downloadFileForURL:(NSString *)urlString
withName:(NSString *)fileName
inDirectoryNamed:(NSString *)directory
friendlyName:(NSString *)friendlyName
progressBlock:(void(^)(CGFloat progress))progressBlock
remainingTime:(void(^)(NSUInteger seconds))remainingTimeBlock
completionBlock:(void(^)(BOOL completed))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!");
} else if (![self fileExistsWithName:fileName inDirectory:directory]) {
NSURLRequest *request = [NSURLRequest requestWithURL:url];
NSURLSessionDownloadTask *downloadTask;
if (backgroundMode) {
downloadTask = [self.backgroundSession downloadTaskWithRequest:request];
} else {
downloadTask = [self.session downloadTaskWithRequest:request];
}
TWRDownloadObject *downloadObject = [[TWRDownloadObject alloc] initWithDownloadTask:downloadTask progressBlock:progressBlock remainingTime:remainingTimeBlock completionBlock:completionBlock];
downloadObject.startDate = [NSDate date];
downloadObject.fileName = fileName;
downloadObject.friendlyName = friendlyName;
downloadObject.directoryName = directory;
[self.downloads addEntriesFromDictionary:@{urlString:downloadObject}];
[downloadTask resume];
} else {
NSLog(@"File already exists!");
}
}
- (void)downloadFileForURL:(NSString *)urlString
withName:(NSString *)fileName
inDirectoryNamed:(NSString *)directory
progressBlock:(void(^)(CGFloat progress))progressBlock
remainingTime:(void(^)(NSUInteger seconds))remainingTimeBlock
completionBlock:(void(^)(BOOL completed))completionBlock
enableBackgroundMode:(BOOL)backgroundMode {
}
- (void)downloadFileForURL:(NSString *)url
inDirectoryNamed:(NSString *)directory
progressBlock:(void(^)(CGFloat progress))progressBlock
remainingTime:(void(^)(NSUInteger seconds))remainingTimeBlock
completionBlock:(void(^)(BOOL completed))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:(void(^)(CGFloat progress))progressBlock
remainingTime:(void(^)(NSUInteger seconds))remainingTimeBlock
completionBlock:(void(^)(BOOL completed))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:(void(^)(CGFloat progress))progressBlock
completionBlock:(void(^)(BOOL completed))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:(void(^)(CGFloat progress))progressBlock
completionBlock:(void(^)(BOOL completed))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:(void(^)(CGFloat progress))progressBlock
completionBlock:(void(^)(BOOL completed))completionBlock
enableBackgroundMode:(BOOL)backgroundMode {
[self downloadFileForURL:urlString
inDirectoryNamed:nil
progressBlock:progressBlock
completionBlock:completionBlock
enableBackgroundMode:backgroundMode];
}
- (void)cancelDownloadForUrl:(NSString *)fileIdentifier {
TWRDownloadObject *download = [self.downloads objectForKey:fileIdentifier];
if (download) {
[download.downloadTask cancel];
[self.downloads removeObjectForKey:fileIdentifier];
if (download.completionBlock) {
download.completionBlock(NO);
}
}
if (self.downloads.count == 0) {
[self cleanTmpDirectory];
}
}
- (void)cancelAllDownloads {
[self.downloads enumerateKeysAndObjectsUsingBlock:^(id key, TWRDownloadObject *download, BOOL *stop) {
if (download.completionBlock) {
download.completionBlock(NO);
}
[download.downloadTask cancel];
[self.downloads removeObjectForKey:key];
}];
[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(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((NSUInteger)remainingTime);
}
});
}
}
- (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(success);
});
}
// remove object from the download
[self.downloads removeObjectForKey: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];
});
}
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
if (error) {
NSLog(@"ERROR: %@", error);
NSString *fileIdentifier = task.originalRequest.URL.absoluteString;
TWRDownloadObject *download = [self.downloads objectForKey:fileIdentifier];
if (download.completionBlock) {
dispatch_async(dispatch_get_main_queue(), ^(void) {
download.completionBlock(NO);
});
}
// remove object from the download
[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:(void(^)(CGFloat progress))block {
return [self isFileDownloadingForUrl:fileIdentifier
withProgressBlock:block
completionBlock:nil];
}
- (BOOL)isFileDownloadingForUrl:(NSString *)fileIdentifier
withProgressBlock:(void(^)(CGFloat progress))block
completionBlock:(void(^)(BOOL completed))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 ([downloadTasks 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();
// Show a local notification when all downloads are over.
UILocalNotification *localNotification = [[UILocalNotification alloc] init];
localNotification.alertBody = @"All files have been downloaded!";
[[UIApplication sharedApplication] presentLocalNotificationNow:localNotification];
}];
// Make nil the backgroundTransferCompletionHandler.
self.backgroundTransferCompletionHandler = nil;
}
}
}];
}
@end