Skip to content

Commit 9632d6a

Browse files
authored
Merge pull request #368 from utkuimd/ios-background
Provided download background support to ios devices
2 parents 69ddb09 + ac1707c commit 9632d6a

File tree

2 files changed

+90
-45
lines changed

2 files changed

+90
-45
lines changed

ios/ReactNativeBlobUtilRequest.h

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@
2020
#import "RCTBridgeModule.h"
2121
#endif
2222

23-
@interface ReactNativeBlobUtilRequest : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate>
23+
@interface ReactNativeBlobUtilRequest : NSObject <NSURLSessionDelegate, NSURLSessionTaskDelegate, NSURLSessionDataDelegate, NSURLSessionDownloadDelegate>
2424

2525
@property (nullable, nonatomic) NSString * taskId;
2626
@property (nonatomic) long long expectedBytes;
@@ -33,7 +33,7 @@
3333
@property (nullable, nonatomic) NSError * error;
3434
@property (nullable, nonatomic) ReactNativeBlobUtilProgress *progressConfig;
3535
@property (nullable, nonatomic) ReactNativeBlobUtilProgress *uploadProgressConfig;
36-
@property (nullable, nonatomic, weak) NSURLSessionDataTask *task;
36+
@property (nullable, nonatomic, weak) NSURLSessionTask *task;
3737

3838
- (void) sendRequest:(NSDictionary * _Nullable )options
3939
contentLength:(long)contentLength

ios/ReactNativeBlobUtilRequest.mm

Lines changed: 88 additions & 43 deletions
Original file line numberDiff line numberDiff line change
@@ -167,9 +167,15 @@ - (void) sendRequest:(__weak NSDictionary * _Nullable )options
167167
respFile = NO;
168168
}
169169

170-
NSURLSessionDataTask *task = [session dataTaskWithRequest:req];
171-
[task resume];
172-
self.task = task;
170+
if(backgroundTask) {
171+
NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:req];
172+
[task resume];
173+
self.task = task;
174+
} else {
175+
NSURLSessionDataTask *task = [session dataTaskWithRequest:req];
176+
[task resume];
177+
self.task = task;
178+
}
173179

174180
// network status indicator
175181
if ([[options objectForKey:CONFIG_INDICATOR] boolValue]) {
@@ -188,6 +194,52 @@ - (void) sendRequest:(__weak NSDictionary * _Nullable )options
188194

189195
#pragma mark NSURLSession delegate methods
190196

197+
- (void)configureWriteStream {
198+
if (respFile)
199+
{
200+
@try{
201+
NSFileManager * fm = [NSFileManager defaultManager];
202+
NSString * folder = [destPath stringByDeletingLastPathComponent];
203+
204+
if (![fm fileExistsAtPath:folder]) {
205+
[fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
206+
}
207+
208+
// if not set overwrite in options, defaults to TRUE
209+
BOOL overwrite = [options valueForKey:@"overwrite"] == nil ? YES : [[options valueForKey:@"overwrite"] boolValue];
210+
BOOL appendToExistingFile = [destPath containsString:@"?append=true"];
211+
212+
appendToExistingFile = !overwrite;
213+
214+
// For solving #141 append response data if the file already exists
215+
// base on PR#139 @kejinliang
216+
if (appendToExistingFile) {
217+
destPath = [destPath stringByReplacingOccurrencesOfString:@"?append=true" withString:@""];
218+
}
219+
220+
if (![fm fileExistsAtPath:destPath]) {
221+
[fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
222+
}
223+
224+
writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:appendToExistingFile];
225+
[writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
226+
[writeStream open];
227+
}
228+
@catch(NSException * ex)
229+
{
230+
NSLog(@"write file error");
231+
}
232+
}
233+
}
234+
235+
- (void)processData:(NSData *)data {
236+
if (respFile && ![self ShouldTransformFile]) {
237+
[writeStream write:(const uint8_t *)[data bytes] maxLength:[data length]];
238+
} else {
239+
[respData appendData:data];
240+
}
241+
}
242+
191243

192244
#pragma mark - Received Response
193245
// set expected content length on response received
@@ -278,41 +330,7 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
278330
NSLog(@"oops");
279331
}
280332

281-
if (respFile)
282-
{
283-
@try{
284-
NSFileManager * fm = [NSFileManager defaultManager];
285-
NSString * folder = [destPath stringByDeletingLastPathComponent];
286-
287-
if (![fm fileExistsAtPath:folder]) {
288-
[fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
289-
}
290-
291-
// if not set overwrite in options, defaults to TRUE
292-
BOOL overwrite = [options valueForKey:@"overwrite"] == nil ? YES : [[options valueForKey:@"overwrite"] boolValue];
293-
BOOL appendToExistingFile = [destPath containsString:@"?append=true"];
294-
295-
appendToExistingFile = !overwrite;
296-
297-
// For solving #141 append response data if the file already exists
298-
// base on PR#139 @kejinliang
299-
if (appendToExistingFile) {
300-
destPath = [destPath stringByReplacingOccurrencesOfString:@"?append=true" withString:@""];
301-
}
302-
303-
if (![fm fileExistsAtPath:destPath]) {
304-
[fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
305-
}
306-
307-
writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:appendToExistingFile];
308-
[writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
309-
[writeStream open];
310-
}
311-
@catch(NSException * ex)
312-
{
313-
NSLog(@"write file error");
314-
}
315-
}
333+
[self configureWriteStream];
316334

317335
completionHandler(NSURLSessionResponseAllow);
318336
}
@@ -339,11 +357,7 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
339357

340358
// If we need to process the data, we defer writing into the file until the we have all the data, at which point
341359
// we can perform the processing and then write into the file
342-
if (respFile && ![self ShouldTransformFile]) {
343-
[writeStream write:(const uint8_t *)[data bytes] maxLength:[data length]];
344-
} else {
345-
[respData appendData:data];
346-
}
360+
[self processData:data];
347361

348362
if (expectedBytes == 0) {
349363
return;
@@ -535,5 +549,36 @@ - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPe
535549
}
536550
}
537551

552+
// NSURLSessionDownloadTask delegates
553+
554+
#pragma mark NSURLSessionDownloadTask delegate methods
555+
556+
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(NSURL *)location {
557+
558+
NSFileManager *fm = [NSFileManager defaultManager];
559+
NSData *data = [fm contentsAtPath:location.path];
560+
561+
[self configureWriteStream];
562+
563+
[self processData:data];
564+
565+
}
566+
567+
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite {
568+
if (totalBytesExpectedToWrite == 0) {
569+
return;
570+
}
571+
572+
NSNumber * now =[NSNumber numberWithFloat:((float)totalBytesWritten/(float)totalBytesExpectedToWrite)];
573+
if ([self.progressConfig shouldReport:now]) {
574+
[self.baseModule emitEventDict:EVENT_PROGRESS
575+
body:@{
576+
@"taskId": taskId,
577+
@"written": [NSString stringWithFormat:@"%lld", (long long) totalBytesWritten],
578+
@"total": [NSString stringWithFormat:@"%lld", (long long) totalBytesExpectedToWrite]
579+
}
580+
];
581+
}
582+
}
538583

539584
@end

0 commit comments

Comments
 (0)