1// Copyright 2015-present 650 Industries. All rights reserved. 2 3#import <ExpoFileSystem/EXSessionResumableDownloadTaskDelegate.h> 4 5@interface EXSessionResumableDownloadTaskDelegate () 6 7@property (strong, nonatomic, readonly) EXDownloadDelegateOnWriteCallback onWriteCallback; 8@property (weak, nonatomic) EXTaskHandlersManager *manager; 9@property (strong, nonatomic) NSString *uuid; 10 11@end 12 13@implementation EXSessionResumableDownloadTaskDelegate 14 15- (nonnull instancetype)initWithResolve:(EXPromiseResolveBlock)resolve 16 reject:(EXPromiseRejectBlock)reject 17 localUrl:(NSURL *)localUrl 18 shouldCalculateMd5:(BOOL)shouldCalculateMd5 19 onWriteCallback:(EXDownloadDelegateOnWriteCallback)onWriteCallback 20 resumableManager:(EXTaskHandlersManager *)manager 21 uuid:(NSString *)uuid; 22{ 23 if (self = [super initWithResolve:resolve 24 reject:reject 25 localUrl:localUrl 26 shouldCalculateMd5:shouldCalculateMd5]) { 27 _onWriteCallback = onWriteCallback; 28 _manager = manager; 29 _uuid = uuid; 30 } 31 return self; 32} 33 34- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location 35{ 36 [super URLSession:session downloadTask:downloadTask didFinishDownloadingToURL:location]; 37 [_manager unregisterTask:_uuid]; 38} 39 40- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error 41{ 42 if (error) { 43 // The task was paused by us. So, we shouldn't throw. 44 if (error.code == NSURLErrorCancelled) { 45 self.resolve([NSNull null]); 46 } else { 47 self.reject(@"ERR_FILESYSTEM_CANNOT_DOWNLOAD", 48 [NSString stringWithFormat:@"Unable to download file: %@", error.description], 49 error); 50 } 51 } 52 53 [_manager unregisterTask:_uuid]; 54} 55 56- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask 57 didWriteData:(int64_t)bytesWritten 58 totalBytesWritten:(int64_t)totalBytesWritten 59 totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite 60{ 61 if (_onWriteCallback && bytesWritten > 0) { 62 _onWriteCallback(downloadTask, bytesWritten, totalBytesWritten, totalBytesExpectedToWrite); 63 } 64} 65 66@end 67