diff --git a/ios/RNBackgroundDownloader.m b/ios/RNBackgroundDownloader.m index 7fd79129..fe971364 100644 --- a/ios/RNBackgroundDownloader.m +++ b/ios/RNBackgroundDownloader.m @@ -105,6 +105,25 @@ + (void)setCompletionHandlerWithIdentifier: (NSString *)identifier completionHan } } +- (NSError *)getServerError: (nonnull NSURLSessionDownloadTask *)downloadTask { + NSError *serverError; + NSInteger httpStatusCode = [((NSHTTPURLResponse *)downloadTask.response) statusCode]; + if(httpStatusCode != 200) { + serverError = [NSError errorWithDomain:NSURLErrorDomain + code:httpStatusCode + userInfo:@{NSLocalizedDescriptionKey: [NSHTTPURLResponse localizedStringForStatusCode: httpStatusCode]}]; + } + return serverError; +} + +- (BOOL)saveDownloadedFile: (nonnull RNBGDTaskConfig *) taskConfig downloadURL:(nonnull NSURL *)location error:(NSError **)saveError { + NSFileManager *fileManager = [NSFileManager defaultManager]; + NSURL *destURL = [NSURL fileURLWithPath:taskConfig.destination]; + [fileManager createDirectoryAtURL:[destURL URLByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil]; + [fileManager removeItemAtURL:destURL error:nil]; + + return [fileManager moveItemAtURL:location toURL:destURL error:saveError]; +} #pragma mark - JS exported methods RCT_EXPORT_METHOD(download: (NSDictionary *) options) { @@ -208,19 +227,17 @@ + (void)setCompletionHandlerWithIdentifier: (NSString *)identifier completionHan #pragma mark - NSURLSessionDownloadDelegate methods - (void)URLSession:(nonnull NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(nonnull NSURL *)location { @synchronized (sharedLock) { - RNBGDTaskConfig *taskCofig = taskToConfigMap[@(downloadTask.taskIdentifier)]; - if (taskCofig != nil) { - NSFileManager *fileManager = [NSFileManager defaultManager]; - NSURL *destURL = [NSURL fileURLWithPath:taskCofig.destination]; - [fileManager createDirectoryAtURL:[destURL URLByDeletingLastPathComponent] withIntermediateDirectories:YES attributes:nil error:nil]; - [fileManager removeItemAtURL:destURL error:nil]; - NSError *moveError; - BOOL moved = [fileManager moveItemAtURL:location toURL:destURL error:&moveError]; + RNBGDTaskConfig *taskConfig = taskToConfigMap[@(downloadTask.taskIdentifier)]; + if (taskConfig != nil) { + NSError *error = [self getServerError:downloadTask]; + if (error == nil) { + [self saveDownloadedFile:taskConfig downloadURL:location error:&error]; + } if (self.bridge) { - if (moved) { - [self sendEventWithName:@"downloadComplete" body:@{@"id": taskCofig.id}]; + if (error == nil) { + [self sendEventWithName:@"downloadComplete" body:@{@"id": taskConfig.id}]; } else { - [self sendEventWithName:@"downloadFailed" body:@{@"id": taskCofig.id, @"error": [moveError localizedDescription]}]; + [self sendEventWithName:@"downloadFailed" body:@{@"id": taskConfig.id, @"error": [error localizedDescription]}]; } } [self removeTaskFromMap:downloadTask];