@kesha-antonov/react-native-background-downloader 4.6.3 → 4.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (41) hide show
  1. package/README.md +29 -7
  2. package/android/src/main/java/com/eko/DownloadConstants.kt +13 -2
  3. package/android/src/main/java/com/eko/DownloadResult.kt +3 -1
  4. package/android/src/main/java/com/eko/Downloader.kt +25 -4
  5. package/android/src/main/java/com/eko/ProgressReporter.kt +14 -35
  6. package/android/src/main/java/com/eko/RNBackgroundDownloaderModuleImpl.kt +162 -76
  7. package/android/src/main/java/com/eko/ResumableDownloadService.kt +2 -1
  8. package/android/src/main/java/com/eko/ResumableDownloader.kt +75 -3
  9. package/android/src/main/java/com/eko/UIDTDownloadJobService.kt +34 -8
  10. package/android/src/main/java/com/eko/Uploader.kt +15 -11
  11. package/android/src/main/java/com/eko/handlers/OnBegin.kt +6 -1
  12. package/android/src/main/java/com/eko/uidt/CancelDownloadReceiver.kt +3 -1
  13. package/android/src/main/java/com/eko/uidt/UIDTJobManager.kt +18 -2
  14. package/android/src/main/java/com/eko/utils/RedirectResolver.kt +5 -13
  15. package/android/src/main/java/com/eko/utils/StorageManager.kt +5 -0
  16. package/android/src/test/java/com/eko/DownloaderRecoveryTest.kt +78 -0
  17. package/android/src/test/java/com/eko/DownloaderResumeTest.kt +97 -0
  18. package/android/src/test/java/com/eko/ResumableDownloaderStallTest.kt +145 -0
  19. package/android/src/test/java/com/eko/UploaderMultipartTest.kt +84 -0
  20. package/android/src/test/java/com/eko/handlers/OnBeginTest.kt +51 -0
  21. package/android/src/test/java/com/eko/uidt/CancelDownloadReceiverTest.kt +84 -0
  22. package/android/src/test/java/com/eko/utils/RedirectResolverTest.kt +67 -0
  23. package/ios/RNBGDTaskConfig.h +2 -0
  24. package/ios/RNBGDTaskConfig.mm +6 -0
  25. package/ios/RNBackgroundDownloader.mm +640 -90
  26. package/lib/DownloadTask.d.ts +2 -0
  27. package/lib/DownloadTask.js +21 -1
  28. package/lib/UploadTask.d.ts +2 -0
  29. package/lib/UploadTask.js +25 -3
  30. package/lib/index.d.ts +1 -1
  31. package/lib/index.js +83 -70
  32. package/lib/tasks.d.ts +4 -0
  33. package/lib/tasks.js +7 -0
  34. package/package.json +14 -11
  35. package/plugin/build/index.d.ts +1 -0
  36. package/plugin/build/index.js +18 -10
  37. package/react-native-background-downloader.podspec +8 -0
  38. package/src/DownloadTask.ts +22 -1
  39. package/src/UploadTask.ts +25 -3
  40. package/src/index.ts +74 -43
  41. package/src/tasks.ts +7 -0
@@ -3,6 +3,7 @@
3
3
  #import "RNBGDUploadTaskConfig.h"
4
4
  #import <MMKV/MMKV.h>
5
5
  #import <React/RCTBridge.h>
6
+ #import <React/RCTUtils.h>
6
7
 
7
8
  #ifdef RCT_NEW_ARCH_ENABLED
8
9
  #import <RNBackgroundDownloaderSpec/RNBackgroundDownloaderSpec.h>
@@ -13,6 +14,7 @@
13
14
  #define ID_TO_UPLOAD_CONFIG_MAP_KEY @"com.eko.bguploadidmap"
14
15
  #define PROGRESS_INTERVAL_KEY @"progressInterval"
15
16
  #define PROGRESS_MIN_BYTES_KEY @"progressMinBytes"
17
+ #define MAX_PARALLEL_DOWNLOADS_KEY @"maxParallelDownloads"
16
18
  // Persisted map of downloads whose finished file could not be moved to its destination
17
19
  // yet because the device was locked (Data Protection). The move is retried when protected
18
20
  // data becomes available / on next launch. See issue #101.
@@ -26,7 +28,15 @@ static const NSTimeInterval kResourceTimeoutSeconds = 60 * 60 * 24; // 1 day -
26
28
  // Progress reporting constants
27
29
  static const NSTimeInterval kTaskReconciliationDelay = 0.1; // Delay to allow session tasks to stabilize
28
30
  static const float kProgressReportThreshold = 0.01f; // Report progress every 1% change
29
- static const NSTimeInterval kCompletionHandlerTimeout = 30.0; // Timeout for completion handler (30 seconds)
31
+ // Fallback for the background completion handler; iOS gives a background launch about 30 s
32
+ static const NSTimeInterval kCompletionHandlerTimeout = 25.0;
33
+ static const NSTimeInterval kSessionInvalidationTimeout = 5.0; // Max wait for a replaced session to go away
34
+ // A download that gets no data for this long while the app is in the foreground is
35
+ // restarted from where it stopped: the system can take many minutes to do it itself
36
+ static const NSTimeInterval kStallTimeout = 20.0;
37
+ static const NSTimeInterval kStallCheckInterval = 5.0;
38
+ // Times in a row a download cut off by the network continues from its resume data
39
+ static const NSInteger kMaxNetworkResumes = 5;
30
40
 
31
41
  // DLog accepts taskId as first parameter to help debugging
32
42
  // Only logs if isLogsEnabled is true (works in both DEBUG and RELEASE builds)
@@ -40,7 +50,61 @@ static const NSTimeInterval kCompletionHandlerTimeout = 30.0; // Timeout for com
40
50
  #define DLogStatic( taskId, s, ... ) do { } while(0)
41
51
  #endif
42
52
 
53
+ // The background session's delegate. A JS reload creates a new module instance, but the
54
+ // session must outlive the old one: invalidating it cancels every transfer in it, and its
55
+ // delegate can't be changed. So the delegate is this object, which hands every call to
56
+ // the newest module instance.
57
+ @interface RNBGDSessionDelegate : NSObject
58
+ @property (atomic, strong) RNBackgroundDownloader *target;
59
+ + (instancetype)shared;
60
+ @end
61
+
62
+ @implementation RNBGDSessionDelegate
63
+
64
+ + (instancetype)shared
65
+ {
66
+ static RNBGDSessionDelegate *shared;
67
+ static dispatch_once_t once;
68
+ dispatch_once(&once, ^{
69
+ shared = [RNBGDSessionDelegate new];
70
+ });
71
+ return shared;
72
+ }
73
+
74
+ - (BOOL)respondsToSelector:(SEL)selector
75
+ {
76
+ return [super respondsToSelector:selector] || [RNBackgroundDownloader instancesRespondToSelector:selector];
77
+ }
78
+
79
+ - (id)forwardingTargetForSelector:(SEL)selector
80
+ {
81
+ return self.target;
82
+ }
83
+
84
+ @end
85
+
86
+ // The session every module instance uses, guarded by the RNBGDSessionDelegate class
87
+ static NSURLSession *sharedSession;
88
+
89
+ // The system's completion handler for a background launch, and what it waits for. Only
90
+ // touched on the main queue.
43
91
  static CompletionHandler storedCompletionHandler;
92
+ // Set when the session has delivered every event of the background launch
93
+ static BOOL backgroundEventsFinished = NO;
94
+ // Tasks whose done or failed event was sent during the launch, not yet passed to completeHandler
95
+ static NSMutableSet<NSString *> *idsAwaitingCompleteHandler;
96
+
97
+ // Calls the completion handler once the session has delivered its events and JS has
98
+ // handled every task that ended in them, so the app isn't suspended mid-way. Main queue.
99
+ static void callCompletionHandlerIfDone(void) {
100
+ if (storedCompletionHandler == nil || !backgroundEventsFinished || idsAwaitingCompleteHandler.count > 0) {
101
+ return;
102
+ }
103
+ CompletionHandler handler = storedCompletionHandler;
104
+ storedCompletionHandler = nil;
105
+ backgroundEventsFinished = NO;
106
+ handler();
107
+ }
44
108
 
45
109
  @implementation RNBackgroundDownloader {
46
110
  MMKV *mmkv;
@@ -69,6 +133,20 @@ static CompletionHandler storedCompletionHandler;
69
133
  NSMutableArray<dispatch_block_t> *pendingDownloads;
70
134
  // Controls whether debug logs are sent to JS
71
135
  BOOL isLogsEnabled;
136
+ // A session being invalidated to be replaced with one with a new configuration, and
137
+ // the signal that it's gone (see -lazyRegisterSession)
138
+ NSURLSession *replacedSession;
139
+ dispatch_semaphore_t replacedSessionInvalidated;
140
+ // When each download last received data, for the stall check
141
+ NSMutableDictionary<NSString *, NSDate *> *idToLastDataAt;
142
+ // Downloads being restarted after a stall; their cancel isn't a pause or a failure
143
+ NSMutableSet<NSString *> *idsBeingRestarted;
144
+ // Times each download continued after the network cut it off, since it last got data
145
+ NSMutableDictionary<NSString *, NSNumber *> *idToNetworkResumeCount;
146
+ NSTimeInterval stallTimeout;
147
+ BOOL isAppActive;
148
+ BOOL hasReconciledTasks;
149
+ dispatch_source_t stallTimer;
72
150
 
73
151
  // Downloads that finished but whose file couldn't be moved to its destination because
74
152
  // the device was locked. Keyed by configId -> staging/destination info. Retried on
@@ -80,6 +158,10 @@ static CompletionHandler storedCompletionHandler;
80
158
  // This prevents crashes (std::bad_function_call / SIGABRT) when NSURLSession delegate
81
159
  // callbacks fire before JS has registered event listeners.
82
160
  NSMutableArray<NSDictionary *> *pendingEmitEvents;
161
+ #else
162
+ // Events waiting for the bridge, in the order they were sent (see -sendEventWithName:body:)
163
+ NSMutableArray<NSDictionary *> *pendingBridgeEvents;
164
+ int bridgeRetryCount;
83
165
  #endif
84
166
 
85
167
  // Upload-specific instance variables
@@ -160,25 +242,54 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
160
242
  // Old architecture override to ensure events are sent
161
243
  // Check if bridge is valid and loaded before sending events
162
244
  - (void)sendEventWithName:(NSString *)eventName body:(id)body {
163
- [self sendEventWithName:eventName body:body retryCount:0];
164
- }
165
-
166
- - (void)sendEventWithName:(NSString *)eventName body:(id)body retryCount:(int)retryCount {
167
- // Check if bridge is available and loaded
168
- // This prevents crashes on first app install when events fire before JS is ready
169
- if (self.bridge == nil || !self.bridge.isValid) {
170
- if (retryCount < kMaxEventRetries) {
171
- DLog(nil, @"[RNBackgroundDownloader] - Bridge not ready (attempt %d), queueing event: %@", retryCount + 1, eventName);
172
- // Queue the event to be sent when bridge becomes available
173
- dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
174
- [self sendEventWithName:eventName body:body retryCount:retryCount + 1];
175
- });
176
- } else {
177
- DLog(nil, @"[RNBackgroundDownloader] - Bridge not ready after %d attempts, dropping event: %@", kMaxEventRetries, eventName);
245
+ [self trackTerminalEvent:eventName body:body];
246
+ @synchronized (pendingBridgeEvents) {
247
+ // While events wait for the bridge, later ones wait behind them, so JS gets them in
248
+ // order (e.g. begin before progress, progress before complete)
249
+ if (pendingBridgeEvents.count > 0 || ![self isBridgeReady]) {
250
+ DLog(nil, @"[RNBackgroundDownloader] - Bridge not ready, queueing event: %@", eventName);
251
+ [pendingBridgeEvents addObject:@{@"name": eventName, @"body": body ?: [NSNull null]}];
252
+ if (pendingBridgeEvents.count == 1) {
253
+ bridgeRetryCount = 0;
254
+ [self scheduleBridgeEventsFlush];
255
+ }
256
+ return;
178
257
  }
179
- return;
258
+ [super sendEventWithName:eventName body:body];
259
+ }
260
+ }
261
+
262
+ // This prevents crashes on first app install when events fire before JS is ready
263
+ - (BOOL)isBridgeReady {
264
+ return self.bridge != nil && self.bridge.isValid;
265
+ }
266
+
267
+ - (void)scheduleBridgeEventsFlush {
268
+ dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
269
+ [self flushBridgeEvents];
270
+ });
271
+ }
272
+
273
+ - (void)flushBridgeEvents {
274
+ @synchronized (pendingBridgeEvents) {
275
+ if (pendingBridgeEvents.count == 0) {
276
+ return;
277
+ }
278
+ if (![self isBridgeReady]) {
279
+ if (++bridgeRetryCount < kMaxEventRetries) {
280
+ [self scheduleBridgeEventsFlush];
281
+ } else {
282
+ DLog(nil, @"[RNBackgroundDownloader] - Bridge not ready after %d attempts, dropping %lu events", kMaxEventRetries, (unsigned long)pendingBridgeEvents.count);
283
+ [pendingBridgeEvents removeAllObjects];
284
+ }
285
+ return;
286
+ }
287
+ for (NSDictionary *event in pendingBridgeEvents) {
288
+ id body = event[@"body"];
289
+ [super sendEventWithName:event[@"name"] body:body == [NSNull null] ? nil : body];
290
+ }
291
+ [pendingBridgeEvents removeAllObjects];
180
292
  }
181
- [super sendEventWithName:eventName body:body];
182
293
  }
183
294
  #endif
184
295
 
@@ -217,7 +328,9 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
217
328
  NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
218
329
  NSString *sessionIdentifier = [bundleIdentifier stringByAppendingString:@".backgrounddownloadtask"];
219
330
  sessionConfig = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:sessionIdentifier];
220
- sessionConfig.HTTPMaximumConnectionsPerHost = kMaxConnectionsPerHost;
331
+ // Saved by setMaxParallelDownloads, so the session is created with it on launch
332
+ NSInteger savedMaxConnections = (NSInteger)[mmkv getInt64ForKey:MAX_PARALLEL_DOWNLOADS_KEY];
333
+ sessionConfig.HTTPMaximumConnectionsPerHost = savedMaxConnections >= 1 ? savedMaxConnections : kMaxConnectionsPerHost;
221
334
  sessionConfig.timeoutIntervalForRequest = kRequestTimeoutSeconds;
222
335
  sessionConfig.timeoutIntervalForResource = kResourceTimeoutSeconds;
223
336
  sessionConfig.discretionary = NO;
@@ -225,6 +338,10 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
225
338
  // These APIs are available since our minimum iOS version (15.1)
226
339
  sessionConfig.shouldUseExtendedBackgroundIdleMode = YES;
227
340
  sessionConfig.allowsExpensiveNetworkAccess = YES;
341
+ // Cellular is restricted per request (isAllowedOverMetered, which defaults to the
342
+ // global setConfig value in JS). The session must stay open: a request can only
343
+ // reliably narrow its session's access, not widen it.
344
+ sessionConfig.allowsCellularAccess = YES;
228
345
 
229
346
  sharedLock = [NSNumber numberWithInt:1];
230
347
 
@@ -248,6 +365,12 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
248
365
  idToUpdatedHeadersMap = [[NSMutableDictionary alloc] init];
249
366
  isSessionActivated = NO;
250
367
  pendingDownloads = [[NSMutableArray alloc] init];
368
+ idToLastDataAt = [[NSMutableDictionary alloc] init];
369
+ idsBeingRestarted = [[NSMutableSet alloc] init];
370
+ idToNetworkResumeCount = [[NSMutableDictionary alloc] init];
371
+ stallTimeout = kStallTimeout;
372
+ isAppActive = YES;
373
+ [self startStallTimer];
251
374
 
252
375
  // Restore any downloads whose file move was deferred because the device was locked
253
376
  NSData *pendingMovesData = [mmkv getDataForKey:PENDING_MOVES_MAP_KEY];
@@ -256,6 +379,8 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
256
379
 
257
380
  #ifdef RCT_NEW_ARCH_ENABLED
258
381
  pendingEmitEvents = [[NSMutableArray alloc] init];
382
+ #else
383
+ pendingBridgeEvents = [[NSMutableArray alloc] init];
259
384
  #endif
260
385
 
261
386
  // Initialize upload-specific data structures
@@ -283,23 +408,48 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
283
408
  return self;
284
409
  }
285
410
 
411
+ // The session isn't invalidated here or on reload: that would cancel every transfer. The
412
+ // next module instance takes it over (see -lazyRegisterSession).
286
413
  - (void)dealloc {
287
414
  DLog(nil, @"[RNBackgroundDownloader] - [dealloc]");
288
- [self unregisterSession];
289
415
  [self unregisterBridgeListener];
290
416
  }
291
417
 
292
418
  - (void)handleBridgeHotReload:(NSNotification *) note {
293
419
  DLog(nil, @"[RNBackgroundDownloader] - [handleBridgeHotReload]");
294
- [self unregisterSession];
295
420
  [self unregisterBridgeListener];
296
421
  }
297
422
 
423
+ // The shared session, created if there's none yet. The session's events go to this
424
+ // instance from now on. Must hold sharedLock.
425
+ - (NSURLSession *)attachSession {
426
+ @synchronized ([RNBGDSessionDelegate class]) {
427
+ // Set first: events can arrive as soon as the session exists, and this instance's
428
+ // state is loaded by now
429
+ [RNBGDSessionDelegate shared].target = self;
430
+ if (sharedSession == nil) {
431
+ sharedSession = [NSURLSession sessionWithConfiguration:sessionConfig
432
+ delegate:(id<NSURLSessionDelegate>)[RNBGDSessionDelegate shared]
433
+ delegateQueue:nil];
434
+ }
435
+ return sharedSession;
436
+ }
437
+ }
438
+
298
439
  - (void)lazyRegisterSession {
299
440
  DLog(nil, @"[RNBackgroundDownloader] - [lazyRegisterSession]");
300
441
  [self sendDebugLog:@"lazyRegisterSession called" taskId:nil];
301
442
  @synchronized (sharedLock) {
302
443
  if (urlSession == nil) {
444
+ if (replacedSession != nil) {
445
+ // A background session created while one with its identifier is still being
446
+ // invalidated is unusable, so wait for -URLSession:didBecomeInvalidWithError:.
447
+ // The replaced session is idle, so nothing on its queue needs this lock.
448
+ [self sendDebugLog:@"lazyRegisterSession: waiting for the replaced session to be invalidated" taskId:nil];
449
+ dispatch_semaphore_wait(replacedSessionInvalidated, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kSessionInvalidationTimeout * NSEC_PER_SEC)));
450
+ replacedSession = nil;
451
+ replacedSessionInvalidated = nil;
452
+ }
303
453
  [self sendDebugLog:@"lazyRegisterSession: creating new session" taskId:nil];
304
454
  // +sessionWithConfiguration: can raise NSInvalidArgumentException (the same
305
455
  // failure mode as issues #161/#170). This is the one choke point every entry
@@ -308,7 +458,7 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
308
458
  // thread. Callers already degrade on a nil session (download queues, the
309
459
  // getExisting* methods reject with ERR_SESSION_NIL).
310
460
  @try {
311
- urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
461
+ urlSession = [self attachSession];
312
462
  // Activate the session by calling getTasksWithCompletionHandler
313
463
  // This forces iOS to fully initialize the background session
314
464
  // On fresh installs, the session may not be ready to process tasks immediately
@@ -347,14 +497,27 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
347
497
  }];
348
498
  }
349
499
 
500
+ // Forgets the shared session, so the next -attachSession creates a new one
501
+ - (void)dropSharedSession:(NSURLSession *)session {
502
+ @synchronized ([RNBGDSessionDelegate class]) {
503
+ if (sharedSession == session) {
504
+ sharedSession = nil;
505
+ }
506
+ }
507
+ }
508
+
509
+ // Invalidates the session, cancelling everything in it. Only for replacing an idle one.
350
510
  - (void)unregisterSession {
351
511
  DLog(nil, @"[RNBackgroundDownloader] - [unregisterSession]");
352
- if (urlSession) {
353
- [urlSession invalidateAndCancel];
354
- urlSession = nil;
512
+ @synchronized (sharedLock) {
513
+ if (urlSession) {
514
+ [self dropSharedSession:urlSession];
515
+ [urlSession invalidateAndCancel];
516
+ urlSession = nil;
517
+ }
518
+ isSessionActivated = NO;
519
+ [pendingDownloads removeAllObjects];
355
520
  }
356
- isSessionActivated = NO;
357
- [pendingDownloads removeAllObjects];
358
521
  }
359
522
 
360
523
  - (void)registerBridgeListener {
@@ -372,6 +535,24 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
372
535
  name:RCTJavaScriptWillStartLoadingNotification
373
536
  object:nil];
374
537
 
538
+ // The stall check runs only while the app is in the foreground
539
+ [[NSNotificationCenter defaultCenter] addObserver:self
540
+ selector:@selector(handleAppActiveChange:)
541
+ name:UIApplicationDidBecomeActiveNotification
542
+ object:nil];
543
+ [[NSNotificationCenter defaultCenter] addObserver:self
544
+ selector:@selector(handleAppActiveChange:)
545
+ name:UIApplicationWillResignActiveNotification
546
+ object:nil];
547
+ dispatch_async(dispatch_get_main_queue(), ^{
548
+ UIApplication *application = RCTSharedApplication();
549
+ if (application != nil) {
550
+ @synchronized (self->sharedLock) {
551
+ self->isAppActive = application.applicationState == UIApplicationStateActive;
552
+ }
553
+ }
554
+ });
555
+
375
556
  // Finish any moves deferred while the device was locked, as soon as
376
557
  // protected data becomes available again (device unlocked). See #101.
377
558
  // Note: the ObjC constant has no "Notification" suffix (unlike most UIApplication ones).
@@ -383,6 +564,136 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
383
564
  }
384
565
  }
385
566
 
567
+ - (void)handleAppActiveChange:(NSNotification *)note {
568
+ @synchronized (sharedLock) {
569
+ isAppActive = [note.name isEqualToString:UIApplicationDidBecomeActiveNotification];
570
+ // Time in the background doesn't count as a stall
571
+ NSDate *now = [NSDate date];
572
+ for (NSString *identifier in [idToLastDataAt allKeys]) {
573
+ idToLastDataAt[identifier] = now;
574
+ }
575
+ }
576
+ }
577
+
578
+ - (void)startStallTimer {
579
+ __weak RNBackgroundDownloader *weakSelf = self;
580
+ stallTimer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, dispatch_get_global_queue(QOS_CLASS_UTILITY, 0));
581
+ dispatch_source_set_timer(stallTimer, dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kStallCheckInterval * NSEC_PER_SEC)), (uint64_t)(kStallCheckInterval * NSEC_PER_SEC), NSEC_PER_SEC);
582
+ dispatch_source_set_event_handler(stallTimer, ^{
583
+ [weakSelf restartStalledDownloads];
584
+ });
585
+ dispatch_resume(stallTimer);
586
+ }
587
+
588
+ // The system retries a stalled background download on its own, but that can take many
589
+ // minutes. While the app is in the foreground, a download that has gone quiet is cancelled
590
+ // with resume data and continued in a new task, which opens a new connection.
591
+ - (void)restartStalledDownloads {
592
+ @synchronized (sharedLock) {
593
+ if (!isAppActive) {
594
+ return;
595
+ }
596
+ NSDate *now = [NSDate date];
597
+ for (NSString *identifier in [idToTaskMap allKeys]) {
598
+ NSURLSessionDownloadTask *task = idToTaskMap[identifier];
599
+ NSDate *lastDataAt = idToLastDataAt[identifier];
600
+ if (task.state != NSURLSessionTaskStateRunning || lastDataAt == nil
601
+ || [now timeIntervalSinceDate:lastDataAt] < stallTimeout
602
+ || [idsBeingRestarted containsObject:identifier] || [idsToPauseSet containsObject:identifier]
603
+ || ![self canResumeTask:task]) {
604
+ continue;
605
+ }
606
+ DLog(identifier, @"[RNBackgroundDownloader] - [restartStalledDownloads] no data for %.0f s, restarting", [now timeIntervalSinceDate:lastDataAt]);
607
+ [idsBeingRestarted addObject:identifier];
608
+ [task cancelByProducingResumeData:^(NSData *resumeData) {
609
+ @synchronized (self->sharedLock) {
610
+ [self->idsBeingRestarted removeObject:identifier];
611
+ RNBGDTaskConfig *taskConfig = self->taskToConfigMap[@(task.taskIdentifier)];
612
+ // Stopped meanwhile
613
+ if (self->idToTaskMap[identifier] != task || taskConfig == nil) {
614
+ return;
615
+ }
616
+ if ([self->idsToPauseSet containsObject:identifier]) {
617
+ // Paused meanwhile: keep the resume data as -pauseTaskInternal: does
618
+ if (resumeData != nil) {
619
+ self->idToResumeDataMap[identifier] = resumeData;
620
+ [self saveResumeData:resumeData forTaskId:identifier];
621
+ taskConfig.hasResumeData = YES;
622
+ }
623
+ taskConfig.state = NSURLSessionTaskStateCanceling;
624
+ taskConfig.errorCode = NSURLErrorCancelled;
625
+ [self->mmkv setData:[self serialize:self->taskToConfigMap] forKey:ID_TO_CONFIG_MAP_KEY];
626
+ return;
627
+ }
628
+ if (![self continueTask:task config:taskConfig resumeData:resumeData]) {
629
+ [self removeTaskFromMap:task];
630
+ [self emitDownloadFailed:identifier error:@"the download stalled and couldn't be continued" errorCode:NSURLErrorTimedOut];
631
+ }
632
+ }
633
+ }];
634
+ }
635
+ }
636
+ }
637
+
638
+ // Resume data needs the server to take ranges and a validator to check the file didn't change
639
+ - (BOOL)canResumeTask:(NSURLSessionTask *)task {
640
+ if (task.countOfBytesReceived <= 0 || ![task.response isKindOfClass:[NSHTTPURLResponse class]]) {
641
+ return NO;
642
+ }
643
+ NSHTTPURLResponse *response = (NSHTTPURLResponse *)task.response;
644
+ NSString *acceptRanges = [response valueForHTTPHeaderField:@"Accept-Ranges"];
645
+ BOOL takesRanges = response.statusCode == 206 || [acceptRanges.lowercaseString containsString:@"bytes"];
646
+ BOOL hasValidator = [response valueForHTTPHeaderField:@"ETag"] != nil || [response valueForHTTPHeaderField:@"Last-Modified"] != nil;
647
+ return takesRanges && hasValidator;
648
+ }
649
+
650
+ // Continues a download from resume data in a new task with the same config. Must hold
651
+ // sharedLock. NO if there's nothing to continue from.
652
+ - (BOOL)continueTask:(NSURLSessionTask *)oldTask config:(RNBGDTaskConfig *)taskConfig resumeData:(NSData *)resumeData {
653
+ if (resumeData == nil) {
654
+ return NO;
655
+ }
656
+ NSURLSessionDownloadTask *newTask = nil;
657
+ @try {
658
+ newTask = [urlSession downloadTaskWithResumeData:resumeData];
659
+ } @catch (NSException *exception) {
660
+ DLog(taskConfig.id, @"[RNBackgroundDownloader] - [continueTask] error: %@", exception.reason);
661
+ }
662
+ if (newTask == nil) {
663
+ return NO;
664
+ }
665
+ [taskToConfigMap removeObjectForKey:@(oldTask.taskIdentifier)];
666
+ taskConfig.state = NSURLSessionTaskStateRunning;
667
+ taskConfig.errorCode = 0;
668
+ taskToConfigMap[@(newTask.taskIdentifier)] = taskConfig;
669
+ [mmkv setData:[self serialize:taskToConfigMap] forKey:ID_TO_CONFIG_MAP_KEY];
670
+ idToTaskMap[taskConfig.id] = newTask;
671
+ idToLastDataAt[taskConfig.id] = [NSDate date];
672
+ [newTask resume];
673
+ return YES;
674
+ }
675
+
676
+ - (BOOL)isNetworkFailure:(NSError *)error {
677
+ if (![error.domain isEqualToString:NSURLErrorDomain]) {
678
+ return NO;
679
+ }
680
+ switch (error.code) {
681
+ case NSURLErrorTimedOut:
682
+ case NSURLErrorNetworkConnectionLost:
683
+ case NSURLErrorNotConnectedToInternet:
684
+ case NSURLErrorCannotConnectToHost:
685
+ case NSURLErrorCannotFindHost:
686
+ case NSURLErrorDNSLookupFailed:
687
+ case NSURLErrorInternationalRoamingOff:
688
+ case NSURLErrorCallIsActive:
689
+ case NSURLErrorDataNotAllowed:
690
+ case NSURLErrorBackgroundSessionWasDisconnected:
691
+ return YES;
692
+ default:
693
+ return NO;
694
+ }
695
+ }
696
+
386
697
  - (void)handleProtectedDataAvailable:(NSNotification *) note {
387
698
  DLog(nil, @"[RNBackgroundDownloader] - [handleProtectedDataAvailable]");
388
699
  [self processPendingMoves];
@@ -434,6 +745,10 @@ static const int kMaxEventRetries = 50; // 50 retries * 100ms = 5 seconds max w
434
745
  [self -> idToTaskMap removeObjectForKey:taskConfig.id];
435
746
  [idToPercentMap removeObjectForKey:taskConfig.id];
436
747
  [idToLastBytesMap removeObjectForKey:taskConfig.id];
748
+ // Progress buffered for a task that's over must not reach JS in a later batch
749
+ [progressReports removeObjectForKey:taskConfig.id];
750
+ [idToLastDataAt removeObjectForKey:taskConfig.id];
751
+ [idToNetworkResumeCount removeObjectForKey:taskConfig.id];
437
752
  // Clean up decode error retry tracking to prevent memory leak
438
753
  [decodeErrorRetriedIds removeObject:taskConfig.id];
439
754
  }
@@ -466,14 +781,31 @@ RCT_EXPORT_METHOD(setLogsEnabled:(BOOL)enabled) {
466
781
  // See https://github.com/kesha-antonov/react-native-background-downloader/issues/161
467
782
  @try {
468
783
  @synchronized (sharedLock) {
469
- if (max >= 1) {
470
- sessionConfig.HTTPMaximumConnectionsPerHost = max;
471
- // Recreate session with new config if it's already initialized
472
- if (urlSession != nil) {
473
- [self unregisterSession];
474
- [self lazyRegisterSession];
475
- }
784
+ if (max < 1 || max == sessionConfig.HTTPMaximumConnectionsPerHost) {
785
+ return;
476
786
  }
787
+ sessionConfig.HTTPMaximumConnectionsPerHost = max;
788
+ [mmkv setInt64:max forKey:MAX_PARALLEL_DOWNLOADS_KEY];
789
+ if (urlSession == nil) {
790
+ return;
791
+ }
792
+ // A live session can't change its config, and recreating it cancels every
793
+ // transfer in it. So recreate it only when it has nothing running; otherwise
794
+ // the saved value applies from the next launch.
795
+ NSURLSession *session = urlSession;
796
+ [session getTasksWithCompletionHandler:^(NSArray *dataTasks, NSArray *uploadTasks, NSArray *downloadTasks) {
797
+ @synchronized (self->sharedLock) {
798
+ BOOL idle = dataTasks.count == 0 && uploadTasks.count == 0 && downloadTasks.count == 0
799
+ && self->pendingDownloads.count == 0
800
+ && self->idToTaskMap.count == 0 && self->idToUploadTaskMap.count == 0;
801
+ if (self->urlSession == session && idle) {
802
+ // The new session is created once this one is gone
803
+ self->replacedSession = session;
804
+ self->replacedSessionInvalidated = dispatch_semaphore_create(0);
805
+ [self unregisterSession];
806
+ }
807
+ }
808
+ }];
477
809
  }
478
810
  } @catch (NSException *exception) {
479
811
  DLog(nil, @"[RNBackgroundDownloader] - [setMaxParallelDownloads] error: %@", exception.reason);
@@ -490,23 +822,19 @@ RCT_EXPORT_METHOD(setMaxParallelDownloads:(NSInteger)max) {
490
822
  }
491
823
  #endif
492
824
 
825
+ #ifdef RCT_NEW_ARCH_ENABLED
826
+ // Notification grouping is Android-only (JS only calls this on Android), but codegen
827
+ // makes the optional spec method required here
828
+ - (void)setNotificationGroupingConfig:(JS::NativeRNBackgroundDownloader::SpecSetNotificationGroupingConfigConfig &)config {
829
+ }
830
+ #endif
831
+
493
832
  - (void)_setAllowsCellularAccessInternal:(BOOL)allows {
494
- DLog(nil, @"[RNBackgroundDownloader] - [setAllowsCellularAccess:%@]", allows ? @"YES" : @"NO");
495
- // Never let an NSException escape this void method - see the note on
496
- // -_setMaxParallelDownloadsInternal: and issue #161. Recreating the session
497
- // here can throw, and an escaping exception crashes Hermes off the JS thread.
498
- @try {
499
- @synchronized (sharedLock) {
500
- sessionConfig.allowsCellularAccess = allows;
501
- // Recreate session with new config if it's already initialized
502
- if (urlSession != nil) {
503
- [self unregisterSession];
504
- [self lazyRegisterSession];
505
- }
506
- }
507
- } @catch (NSException *exception) {
508
- DLog(nil, @"[RNBackgroundDownloader] - [setAllowsCellularAccess] error: %@", exception.reason);
509
- }
833
+ // The global setting is applied in JS as the default for each task's
834
+ // isAllowedOverMetered, which sets the request's allowsCellularAccess. The session
835
+ // keeps allowing cellular, so there's nothing to change here and no session to
836
+ // recreate. Kept so the native API stays the same.
837
+ DLog(nil, @"[RNBackgroundDownloader] - [setAllowsCellularAccess:%@] applied per task", allows ? @"YES" : @"NO");
510
838
  }
511
839
 
512
840
  #ifdef RCT_NEW_ARCH_ENABLED
@@ -528,6 +856,7 @@ RCT_EXPORT_METHOD(setAllowsCellularAccess:(BOOL)allows) {
528
856
  NSString *metadata = options.metadata() ? options.metadata() : @"";
529
857
  NSDictionary *headers = options.headers() ? (NSDictionary *)options.headers() : nil;
530
858
  NSString *dataProtection = options.iosDataProtection() ? options.iosDataProtection() : nil;
859
+ BOOL allowsCellularAccess = options.isAllowedOverMetered();
531
860
 
532
861
  if (options.progressInterval().has_value()) {
533
862
  progressInterval = options.progressInterval().value() / 1000.0;
@@ -549,6 +878,8 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
549
878
  NSString *metadata = options[@"metadata"] ?: @"";
550
879
  NSDictionary *headers = options[@"headers"];
551
880
  NSString *dataProtection = options[@"iosDataProtection"];
881
+ NSNumber *isAllowedOverMetered = options[@"isAllowedOverMetered"];
882
+ BOOL allowsCellularAccess = isAllowedOverMetered == nil || [isAllowedOverMetered boolValue];
552
883
 
553
884
  NSNumber *progressIntervalScope = options[@"progressInterval"];
554
885
  if (progressIntervalScope) {
@@ -568,15 +899,21 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
568
899
  DLog(identifier, @"[RNBackgroundDownloader] - [download] url %@ destination %@ progressInterval %f", url, destination, progressInterval);
569
900
  if (identifier == nil || url == nil || destination == nil) {
570
901
  DLog(identifier, @"[RNBackgroundDownloader] - [Error] id, url and destination must be set");
902
+ [self emitDownloadFailed:identifier error:@"id, url and destination must be set" errorCode:-1];
571
903
  return;
572
904
  }
573
905
 
574
906
  if (destinationRelative == nil) {
575
907
  DLog(identifier, @"[RNBackgroundDownloader] - [Error] destination is not valid");
908
+ [self emitDownloadFailed:identifier error:@"destination is not valid" errorCode:-1];
576
909
  return;
577
910
  }
578
911
 
579
912
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:url]];
913
+ // NOTE: iOS may not allow a request to restrict cellular access further
914
+ // than its session allows.
915
+ // https://developer.apple.com/documentation/foundation/nsmutableurlrequest/allowscellularaccess
916
+ request.allowsCellularAccess = allowsCellularAccess;
580
917
  // Query in the getExistingDownloadTasks function.
581
918
  [request setValue:identifier forHTTPHeaderField:@"configId"];
582
919
  if (headers != nil) {
@@ -616,6 +953,7 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
616
953
  } @catch (NSException *exception) {
617
954
  DLog(identifier, @"[RNBackgroundDownloader] - [download] error: %@", exception.reason);
618
955
  [self sendDebugLog:[NSString stringWithFormat:@"download: ERROR - %@", exception.reason] taskId:identifier];
956
+ [self emitDownloadFailed:identifier error:exception.reason errorCode:-1];
619
957
  }
620
958
  }
621
959
 
@@ -629,6 +967,7 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
629
967
  if (task == nil) {
630
968
  DLog(identifier, @"[RNBackgroundDownloader] - [Error] failed to create download task");
631
969
  [self sendDebugLog:@"executeDownloadWithRequest: ERROR - failed to create download task" taskId:identifier];
970
+ [self emitDownloadFailed:identifier error:@"failed to create download task" errorCode:-1];
632
971
  return;
633
972
  }
634
973
 
@@ -642,6 +981,7 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
642
981
  }];
643
982
  // nil means "use the library default" when saving the file (see -nsFileProtectionFromKey:)
644
983
  taskConfig.dataProtection = dataProtection;
984
+ taskConfig.allowsCellularAccess = request.allowsCellularAccess;
645
985
 
646
986
  taskToConfigMap[@(task.taskIdentifier)] = taskConfig;
647
987
  [mmkv setData:[self serialize: taskToConfigMap] forKey:ID_TO_CONFIG_MAP_KEY];
@@ -652,7 +992,6 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
652
992
 
653
993
  [task resume];
654
994
  [self sendDebugLog:@"executeDownloadWithRequest: task.resume() called" taskId:identifier];
655
- lastProgressReportedAt = [[NSDate alloc] init];
656
995
  }
657
996
  }
658
997
 
@@ -673,7 +1012,8 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
673
1012
 
674
1013
  // Recreate the background session directly (do not call unregisterSession,
675
1014
  // which would invalidateAndCancel and drop queued downloads).
676
- urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
1015
+ [self dropSharedSession:urlSession];
1016
+ urlSession = [self attachSession];
677
1017
  isSessionActivated = YES;
678
1018
 
679
1019
  @try {
@@ -700,7 +1040,8 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
700
1040
 
701
1041
  // Recreate the background session directly (do not call unregisterSession,
702
1042
  // which would invalidateAndCancel and drop queued downloads).
703
- urlSession = [NSURLSession sessionWithConfiguration:sessionConfig delegate:self delegateQueue:nil];
1043
+ [self dropSharedSession:urlSession];
1044
+ urlSession = [self attachSession];
704
1045
  isSessionActivated = YES;
705
1046
 
706
1047
  @try {
@@ -713,6 +1054,24 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
713
1054
  }
714
1055
  }
715
1056
 
1057
+ // Emits downloadFailed so the JS task errors out instead of hanging when download
1058
+ // setup fails before a task exists (bad params, bad destination, task creation failure).
1059
+ - (void)emitDownloadFailed:(NSString *)identifier error:(NSString *)error errorCode:(NSInteger)errorCode {
1060
+ if (identifier == nil) {
1061
+ return;
1062
+ }
1063
+ NSDictionary *body = @{
1064
+ @"id": identifier,
1065
+ @"error": error ?: @"unknown error",
1066
+ @"errorCode": @(errorCode)
1067
+ };
1068
+ #ifdef RCT_NEW_ARCH_ENABLED
1069
+ [self safeEmitEvent:@"onDownloadFailed" value:body];
1070
+ #else
1071
+ [self sendEventWithName:@"downloadFailed" body:body];
1072
+ #endif
1073
+ }
1074
+
716
1075
  // Emits uploadFailed so the JS task errors out instead of hanging when upload
717
1076
  // setup fails before a task exists (bad params, unreadable file, task creation failure).
718
1077
  - (void)emitUploadFailed:(NSString *)identifier error:(NSString *)error errorCode:(NSInteger)errorCode {
@@ -739,6 +1098,7 @@ RCT_EXPORT_METHOD(download: (NSDictionary *) options) {
739
1098
  if (task != nil) {
740
1099
  // Mark task as pausing IMMEDIATELY before cancellation to prevent race condition
741
1100
  [idsToPauseSet addObject:identifier];
1101
+ [progressReports removeObjectForKey:identifier];
742
1102
  DLog(identifier, @"[RNBackgroundDownloader] - [pauseTask] marking task as pausing: %@", identifier);
743
1103
 
744
1104
  [task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
@@ -784,6 +1144,21 @@ RCT_EXPORT_METHOD(pauseTask:(NSString *)id resolver:(RCTPromiseResolveBlock)reso
784
1144
  }
785
1145
  #endif
786
1146
 
1147
+ // A request that downloads the whole file again: the task's own cellular setting and
1148
+ // the given headers, minus any Range
1149
+ - (NSMutableURLRequest *)freshRequestForConfig:(RNBGDTaskConfig *)taskConfig headers:(NSDictionary *)headers {
1150
+ NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:taskConfig.url]];
1151
+ request.allowsCellularAccess = taskConfig.allowsCellularAccess;
1152
+ for (NSString *headerKey in headers) {
1153
+ if ([headerKey caseInsensitiveCompare:@"Range"] == NSOrderedSame) {
1154
+ continue;
1155
+ }
1156
+ [request setValue:[headers valueForKey:headerKey] forHTTPHeaderField:headerKey];
1157
+ }
1158
+ [request setValue:taskConfig.id forHTTPHeaderField:@"configId"];
1159
+ return request;
1160
+ }
1161
+
787
1162
  - (void)resumeTaskInternal:(NSString *)identifier resolve:(RCTPromiseResolveBlock)resolve reject:(RCTPromiseRejectBlock)reject {
788
1163
  DLog(identifier, @"[RNBackgroundDownloader] - [resumeTask]");
789
1164
  @try {
@@ -816,19 +1191,17 @@ RCT_EXPORT_METHOD(pauseTask:(NSString *)id resolver:(RCTPromiseResolveBlock)reso
816
1191
  // This is needed when auth tokens change while paused
817
1192
  if (updatedHeaders != nil && [updatedHeaders count] > 0) {
818
1193
  RNBGDTaskConfig *taskConfig = [self findConfigById:identifier];
819
- if (taskConfig != nil && taskConfig.bytesDownloaded > 0) {
820
- DLog(identifier, @"[RNBackgroundDownloader] - [resumeTask] using updated headers with Range for %@", identifier);
821
- NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:taskConfig.url]];
822
- [request setValue:identifier forHTTPHeaderField:@"configId"];
823
- for (NSString *headerKey in updatedHeaders) {
824
- [request setValue:[updatedHeaders valueForKey:headerKey] forHTTPHeaderField:headerKey];
825
- }
826
- // Add Range header to resume from where we left off
827
- NSString *rangeValue = [NSString stringWithFormat:@"bytes=%lld-", taskConfig.bytesDownloaded];
828
- [request setValue:rangeValue forHTTPHeaderField:@"Range"];
829
- newTask = [urlSession downloadTaskWithRequest:request];
1194
+ if (taskConfig != nil) {
1195
+ // Resume data carries the old headers and can't be changed, and a fresh
1196
+ // task with a Range header saves only the remaining bytes as the whole
1197
+ // file. So download the file again with the new headers.
1198
+ DLog(identifier, @"[RNBackgroundDownloader] - [resumeTask] restarting with updated headers for %@", identifier);
1199
+ newTask = [self createDownloadTaskWithRequest:[self freshRequestForConfig:taskConfig headers:updatedHeaders] identifier:identifier];
1200
+ taskConfig.bytesDownloaded = 0;
1201
+ // Progress thresholds compare with the last report, which was for the old transfer
1202
+ idToPercentMap[identifier] = @0.0;
1203
+ idToLastBytesMap[identifier] = @0;
830
1204
  } else {
831
- // No bytes downloaded, just use resume data (shouldn't normally happen)
832
1205
  newTask = [urlSession downloadTaskWithResumeData:resumeData];
833
1206
  }
834
1207
  // Clear updated headers after use
@@ -868,6 +1241,8 @@ RCT_EXPORT_METHOD(pauseTask:(NSString *)id resolver:(RCTPromiseResolveBlock)reso
868
1241
  // Delete the resume data file after successful resume
869
1242
  [self deleteResumeDataForTaskId:identifier];
870
1243
  [newTask resume];
1244
+ } else {
1245
+ [self emitDownloadFailed:identifier error:@"failed to create download task" errorCode:-1];
871
1246
  }
872
1247
  } else if (task != nil && task.state == NSURLSessionTaskStateSuspended) {
873
1248
  // Task was suspended normally, just resume it
@@ -879,7 +1254,35 @@ RCT_EXPORT_METHOD(pauseTask:(NSString *)id resolver:(RCTPromiseResolveBlock)reso
879
1254
  }
880
1255
  [task resume];
881
1256
  } else {
882
- DLog(identifier, @"[RNBackgroundDownloader] - [resumeTask] no task or resume data found for %@", identifier);
1257
+ // Paused without resume data (the server doesn't support resuming), or the
1258
+ // paused task is gone: download the file again instead of staying paused forever
1259
+ RNBGDTaskConfig *taskConfig = [self findConfigById:identifier];
1260
+ if (taskConfig != nil) {
1261
+ DLog(identifier, @"[RNBackgroundDownloader] - [resumeTask] no resume data, restarting %@", identifier);
1262
+ NSDictionary *headers = updatedHeaders ?: task.originalRequest.allHTTPHeaderFields;
1263
+ NSURLSessionDownloadTask *newTask = [self createDownloadTaskWithRequest:[self freshRequestForConfig:taskConfig headers:headers] identifier:identifier];
1264
+ [idToUpdatedHeadersMap removeObjectForKey:identifier];
1265
+ if (newTask != nil) {
1266
+ NSNumber *oldKey = [self findTaskKeyById:identifier];
1267
+ if (oldKey != nil) {
1268
+ [taskToConfigMap removeObjectForKey:oldKey];
1269
+ }
1270
+ taskConfig.state = NSURLSessionTaskStateRunning;
1271
+ taskConfig.errorCode = 0;
1272
+ taskConfig.hasResumeData = NO;
1273
+ taskConfig.bytesDownloaded = 0;
1274
+ idToPercentMap[identifier] = @0.0;
1275
+ idToLastBytesMap[identifier] = @0;
1276
+ taskToConfigMap[@(newTask.taskIdentifier)] = taskConfig;
1277
+ [mmkv setData:[self serialize: taskToConfigMap] forKey:ID_TO_CONFIG_MAP_KEY];
1278
+ self->idToTaskMap[identifier] = newTask;
1279
+ [newTask resume];
1280
+ } else {
1281
+ [self emitDownloadFailed:identifier error:@"failed to create download task" errorCode:-1];
1282
+ }
1283
+ } else {
1284
+ DLog(identifier, @"[RNBackgroundDownloader] - [resumeTask] no task or resume data found for %@", identifier);
1285
+ }
883
1286
  }
884
1287
  }
885
1288
  resolve(nil);
@@ -985,10 +1388,10 @@ RCT_EXPORT_METHOD(updateTaskHeaders:(NSString *)id headers:(NSDictionary *)heade
985
1388
  DLog(nil, @"[RNBackgroundDownloader] - [completeHandlerIOS]");
986
1389
  @try {
987
1390
  [[NSOperationQueue mainQueue] addOperationWithBlock:^{
988
- if (storedCompletionHandler) {
989
- storedCompletionHandler();
990
- storedCompletionHandler = nil;
1391
+ if (jobId != nil) {
1392
+ [idsAwaitingCompleteHandler removeObject:jobId];
991
1393
  }
1394
+ callCompletionHandlerIfDone();
992
1395
  }];
993
1396
 
994
1397
  resolve(nil);
@@ -1022,8 +1425,13 @@ RCT_EXPORT_METHOD(completeHandler:(nonnull NSString *)jobId resolver:(RCTPromise
1022
1425
  NSString *logMsg = [NSString stringWithFormat:@"getExistingDownloadTasks: found %lu download tasks", (unsigned long)downloadTasks.count];
1023
1426
  [self sendDebugLog:logMsg taskId:nil];
1024
1427
 
1025
- // Wait for session tasks to stabilize after app restart
1026
- [NSThread sleepForTimeInterval:kTaskReconciliationDelay];
1428
+ // Wait for session tasks to stabilize after app restart. Only the first time:
1429
+ // this blocks the session's queue, and so every download's events, and apps
1430
+ // call this for every download they start, pause or stop
1431
+ if (!self->hasReconciledTasks) {
1432
+ self->hasReconciledTasks = YES;
1433
+ [NSThread sleepForTimeInterval:kTaskReconciliationDelay];
1434
+ }
1027
1435
 
1028
1436
  NSMutableArray *foundTasks = [[NSMutableArray alloc] init];
1029
1437
  NSMutableSet *processedIds = [[NSMutableSet alloc] init];
@@ -1035,6 +1443,10 @@ RCT_EXPORT_METHOD(completeHandler:(nonnull NSString *)jobId resolver:(RCTPromise
1035
1443
  if (taskConfig) {
1036
1444
  NSURLSessionDownloadTask *mutableTask = task;
1037
1445
  [self restoreTaskIfNeeded:&mutableTask];
1446
+ if (mutableTask != task) {
1447
+ // The replacement gets its own key below; drop the finished task's
1448
+ [self->taskToConfigMap removeObjectForKey:@(task.taskIdentifier)];
1449
+ }
1038
1450
  [self updateTaskMappings:mutableTask config:taskConfig];
1039
1451
  [foundTasks addObject:[self createTaskInfo:mutableTask config:taskConfig]];
1040
1452
  [processedIds addObject:taskConfig.id];
@@ -1102,17 +1514,18 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1102
1514
  - (void)restoreTaskIfNeeded:(NSURLSessionDownloadTask *__strong *)taskPtr {
1103
1515
  NSURLSessionDownloadTask *task = *taskPtr;
1104
1516
 
1105
- BOOL isCompletedOrSuspended = (task.state == NSURLSessionTaskStateCompleted ||
1106
- task.state == NSURLSessionTaskStateSuspended);
1517
+ // A suspended task can still be resumed as is (see -resumeTaskInternal:); only a
1518
+ // finished, incomplete one needs a replacement
1107
1519
  BOOL needsMoreData = task.countOfBytesReceived < task.countOfBytesExpectedToReceive;
1108
1520
 
1109
- if (isCompletedOrSuspended && needsMoreData) {
1521
+ if (task.state == NSURLSessionTaskStateCompleted && needsMoreData) {
1110
1522
  NSData *resumeData = task.error.userInfo[NSURLSessionDownloadTaskResumeData];
1111
1523
 
1112
1524
  if (task.error.code == -999 && resumeData) {
1113
1525
  *taskPtr = [urlSession downloadTaskWithResumeData:resumeData];
1114
- } else {
1115
- *taskPtr = [urlSession downloadTaskWithURL:task.currentRequest.URL];
1526
+ } else if (task.originalRequest != nil) {
1527
+ // The original request keeps the configId header, custom headers and cellular flag
1528
+ *taskPtr = [urlSession downloadTaskWithRequest:task.originalRequest];
1116
1529
  }
1117
1530
  }
1118
1531
  }
@@ -1317,6 +1730,7 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1317
1730
  // when NSURLSession delegate callbacks fire before JS has registered listeners
1318
1731
  // (e.g., background session delivering completions from a prior app session).
1319
1732
  - (void)safeEmitEvent:(NSString *)eventName value:(id)value {
1733
+ [self trackTerminalEvent:eventName body:value];
1320
1734
  @synchronized (pendingEmitEvents) {
1321
1735
  if (_eventEmitterCallback) {
1322
1736
  _eventEmitterCallback(std::string([eventName UTF8String]), value);
@@ -1339,6 +1753,21 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1339
1753
  }
1340
1754
  #endif
1341
1755
 
1756
+ #pragma mark - NSURLSessionDelegate methods
1757
+
1758
+ - (void)URLSession:(NSURLSession *)session didBecomeInvalidWithError:(NSError *)error {
1759
+ // Set before the session was invalidated, so they're safe to read here. Signal before
1760
+ // taking the lock: -lazyRegisterSession may be holding it while it waits for this.
1761
+ dispatch_semaphore_t invalidated = replacedSessionInvalidated;
1762
+ if (session != replacedSession || invalidated == nil) {
1763
+ return;
1764
+ }
1765
+ DLog(nil, @"[RNBackgroundDownloader] - [didBecomeInvalidWithError] replaced session invalidated");
1766
+ dispatch_semaphore_signal(invalidated);
1767
+ // Create its replacement now, unless something needed the session first
1768
+ [self lazyRegisterSession];
1769
+ }
1770
+
1342
1771
  #pragma mark - NSURLSessionDownloadDelegate methods
1343
1772
  - (void)URLSession:(nonnull NSURLSession *)session downloadTask:(nonnull NSURLSessionDownloadTask *)downloadTask didFinishDownloadingToURL:(nonnull NSURL *)location {
1344
1773
  @synchronized (sharedLock) {
@@ -1395,17 +1824,19 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1395
1824
  }];
1396
1825
  #endif
1397
1826
  } else {
1827
+ // Where -saveFile: put it, which differs from the stored path after an app update
1828
+ NSString *location = [self currentPathForDestination:taskConfig.destination] ?: taskConfig.destination;
1398
1829
  #ifdef RCT_NEW_ARCH_ENABLED
1399
1830
  [self safeEmitEvent:@"onDownloadComplete" value:@{
1400
1831
  @"id": taskConfig.id,
1401
- @"location": taskConfig.destination,
1832
+ @"location": location,
1402
1833
  @"bytesDownloaded": @(task.countOfBytesReceived),
1403
1834
  @"bytesTotal": @(task.countOfBytesExpectedToReceive)
1404
1835
  }];
1405
1836
  #else
1406
1837
  [self sendEventWithName:@"downloadComplete" body:@{
1407
1838
  @"id": taskConfig.id,
1408
- @"location": taskConfig.destination,
1839
+ @"location": location,
1409
1840
  @"bytesDownloaded": @(task.countOfBytesReceived),
1410
1841
  @"bytesTotal": @(task.countOfBytesExpectedToReceive)
1411
1842
  }];
@@ -1434,6 +1865,9 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1434
1865
 
1435
1866
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [didWriteData]");
1436
1867
 
1868
+ idToLastDataAt[taskConfig.id] = [NSDate date];
1869
+ [idToNetworkResumeCount removeObjectForKey:taskConfig.id];
1870
+
1437
1871
  [self reportBeginIfNeeded:taskConfig downloadTask:downloadTask expectedBytes:bytesTotalExpectedToWrite];
1438
1872
  [self updateProgressIfNeeded:taskConfig bytesWritten:bytesTotalWritten bytesTotal:bytesTotalExpectedToWrite];
1439
1873
  [self flushProgressReportsIfNeeded];
@@ -1471,6 +1905,10 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1471
1905
  }
1472
1906
 
1473
1907
  - (void)updateProgressIfNeeded:(RNBGDTaskConfig *)taskConfig bytesWritten:(int64_t)bytesWritten bytesTotal:(int64_t)bytesTotal {
1908
+ // Data already in flight when the app paused the task
1909
+ if ([idsToPauseSet containsObject:taskConfig.id]) {
1910
+ return;
1911
+ }
1474
1912
  NSNumber *prevPercent = idToPercentMap[taskConfig.id] ?: @0.0;
1475
1913
  NSNumber *prevBytes = idToLastBytesMap[taskConfig.id] ?: @0;
1476
1914
  float currentPercent = bytesTotal > 0 ? (float)bytesWritten / (float)bytesTotal : 0.0;
@@ -1532,10 +1970,27 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1532
1970
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [didCompleteWithError] error: %@", error);
1533
1971
  [self sendDebugLog:[NSString stringWithFormat:@"didCompleteWithError: error code=%ld, %@", (long)error.code, error.localizedDescription] taskId:taskConfig.id];
1534
1972
 
1973
+ // Cancelled to be restarted after a stall (-restartStalledDownloads:)
1974
+ if ([idsBeingRestarted containsObject:taskConfig.id]) {
1975
+ return;
1976
+ }
1977
+
1535
1978
  // NSURLErrorCancelled (-999) is used for paused or cancelled tasks
1536
1979
  // Extract resume data first before checking isPausedTask
1537
1980
  NSData *resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
1538
1981
 
1982
+ // Cut off by the network (timeout, lost connection): continue from the resume data
1983
+ // the system handed over, as it does itself for a stall, instead of failing the task.
1984
+ // Bounded, as a server that always cuts it off would loop
1985
+ if (resumeData != nil && [self isNetworkFailure:error]) {
1986
+ NSInteger resumes = [idToNetworkResumeCount[taskConfig.id] integerValue];
1987
+ if (resumes < kMaxNetworkResumes && [self continueTask:task config:taskConfig resumeData:resumeData]) {
1988
+ idToNetworkResumeCount[taskConfig.id] = @(resumes + 1);
1989
+ DLog(taskConfig.id, @"[RNBackgroundDownloader] - [didCompleteWithError] network failure, continuing (%ld)", (long)resumes + 1);
1990
+ return;
1991
+ }
1992
+ }
1993
+
1539
1994
  // Check if this task was intentionally paused (marked in idsToPauseSet)
1540
1995
  BOOL wasIntentionallyPaused = [idsToPauseSet containsObject:taskConfig.id];
1541
1996
  BOOL hasResumeData = resumeData != nil;
@@ -1544,10 +1999,16 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1544
1999
  if (isPausedTask) {
1545
2000
  taskConfig.errorCode = error.code;
1546
2001
 
1547
- // Store resume data so we can resume the download later
2002
+ // Store resume data so we can resume the download later. Persist it too, as
2003
+ // -pauseTaskInternal: does: a cancel the app didn't ask for (e.g. the system
2004
+ // cancelling the task) would otherwise lose it on the next launch
1548
2005
  if (taskConfig.id && resumeData) {
1549
2006
  idToResumeDataMap[taskConfig.id] = resumeData;
2007
+ [self saveResumeData:resumeData forTaskId:taskConfig.id];
2008
+ taskConfig.hasResumeData = YES;
1550
2009
  }
2010
+ taskConfig.state = NSURLSessionTaskStateCanceling;
2011
+ [mmkv setData:[self serialize:taskToConfigMap] forKey:ID_TO_CONFIG_MAP_KEY];
1551
2012
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [didCompleteWithError] task was paused, ignoring error for %@", taskConfig.id);
1552
2013
  return;
1553
2014
  }
@@ -1563,6 +2024,8 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1563
2024
 
1564
2025
  // Build a fresh request replicating original headers
1565
2026
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:taskConfig.url]];
2027
+ // Keep the original request's cellular access
2028
+ request.allowsCellularAccess = taskConfig.allowsCellularAccess;
1566
2029
  // Reapply original request headers if available (including our internal identifier header)
1567
2030
  NSDictionary *originalHeaders = task.originalRequest.allHTTPHeaderFields;
1568
2031
  if (originalHeaders != nil) {
@@ -1615,6 +2078,33 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1615
2078
 
1616
2079
  - (void)URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session {
1617
2080
  DLog(nil, @"[RNBackgroundDownloader] - [URLSessionDidFinishEventsForBackgroundURLSession]");
2081
+ // Queued after the ids of the events just sent (-trackTerminalEvent:body:), so they count
2082
+ dispatch_async(dispatch_get_main_queue(), ^{
2083
+ backgroundEventsFinished = YES;
2084
+ callCompletionHandlerIfDone();
2085
+ });
2086
+ }
2087
+
2088
+ // Remembers a task whose done or failed event is sent during a background launch: the
2089
+ // completion handler waits until JS passes it to completeHandler
2090
+ - (void)trackTerminalEvent:(NSString *)eventName body:(id)body {
2091
+ static NSSet<NSString *> *terminalEvents;
2092
+ static dispatch_once_t once;
2093
+ dispatch_once(&once, ^{
2094
+ terminalEvents = [NSSet setWithArray:@[
2095
+ @"downloadComplete", @"downloadFailed", @"uploadComplete", @"uploadFailed",
2096
+ @"onDownloadComplete", @"onDownloadFailed", @"onUploadComplete", @"onUploadFailed",
2097
+ ]];
2098
+ });
2099
+ NSString *identifier = [body isKindOfClass:[NSDictionary class]] ? body[@"id"] : nil;
2100
+ if (identifier == nil || ![terminalEvents containsObject:eventName]) {
2101
+ return;
2102
+ }
2103
+ dispatch_async(dispatch_get_main_queue(), ^{
2104
+ if (storedCompletionHandler != nil) {
2105
+ [idsAwaitingCompleteHandler addObject:identifier];
2106
+ }
2107
+ });
1618
2108
  }
1619
2109
 
1620
2110
  #pragma mark - Upload methods
@@ -1632,6 +2122,7 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1632
2122
  [idToUploadTaskMap removeObjectForKey:taskConfig.id];
1633
2123
  [idToUploadPercentMap removeObjectForKey:taskConfig.id];
1634
2124
  [idToUploadLastBytesMap removeObjectForKey:taskConfig.id];
2125
+ [uploadProgressReports removeObjectForKey:taskConfig.id];
1635
2126
  }
1636
2127
  }
1637
2128
  }
@@ -1648,6 +2139,7 @@ RCT_EXPORT_METHOD(getExistingDownloadTasks: (RCTPromiseResolveBlock)resolve reje
1648
2139
  NSString *fieldName = options.fieldName() ? options.fieldName() : nil;
1649
2140
  NSString *mimeType = options.mimeType() ? options.mimeType() : nil;
1650
2141
  NSDictionary *parameters = options.parameters() ? (NSDictionary *)options.parameters() : nil;
2142
+ BOOL allowsCellularAccess = options.isAllowedOverMetered();
1651
2143
 
1652
2144
  if (options.progressInterval().has_value()) {
1653
2145
  progressInterval = options.progressInterval().value() / 1000.0;
@@ -1670,6 +2162,8 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
1670
2162
  NSString *fieldName = options[@"fieldName"];
1671
2163
  NSString *mimeType = options[@"mimeType"];
1672
2164
  NSDictionary *parameters = options[@"parameters"];
2165
+ NSNumber *isAllowedOverMetered = options[@"isAllowedOverMetered"];
2166
+ BOOL allowsCellularAccess = isAllowedOverMetered == nil || [isAllowedOverMetered boolValue];
1673
2167
 
1674
2168
  NSNumber *progressIntervalScope = options[@"progressInterval"];
1675
2169
  if (progressIntervalScope) {
@@ -1729,6 +2223,7 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
1729
2223
  // Create request
1730
2224
  NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:requestURL];
1731
2225
  request.HTTPMethod = method;
2226
+ request.allowsCellularAccess = allowsCellularAccess;
1732
2227
  [request setValue:identifier forHTTPHeaderField:@"uploadConfigId"];
1733
2228
 
1734
2229
  // Add custom headers
@@ -1796,7 +2291,7 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
1796
2291
  [body appendData:[[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
1797
2292
 
1798
2293
  // Write body to temp file for background upload
1799
- NSString *tempPath = [NSTemporaryDirectory() stringByAppendingPathComponent:[[NSUUID UUID] UUIDString]];
2294
+ NSString *tempPath = [self multipartTempPathForUploadId:identifier];
1800
2295
  if (![body writeToFile:tempPath atomically:YES]) {
1801
2296
  DLog(identifier, @"[RNBackgroundDownloader] - [Error] Could not write multipart body to temp file");
1802
2297
  [self emitUploadFailed:identifier error:@"Could not write multipart body to temp file" errorCode:NSURLErrorCannotWriteToFile];
@@ -1816,6 +2311,7 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
1816
2311
 
1817
2312
  if (uploadTask == nil) {
1818
2313
  DLog(identifier, @"[RNBackgroundDownloader] - [Error] failed to create upload task");
2314
+ [self removeMultipartTempFileForUploadId:identifier];
1819
2315
  [self emitUploadFailed:identifier error:@"failed to create upload task" errorCode:-1];
1820
2316
  return;
1821
2317
  }
@@ -1828,7 +2324,6 @@ RCT_EXPORT_METHOD(upload:(NSDictionary *)options) {
1828
2324
  idToUploadLastBytesMap[identifier] = @0;
1829
2325
 
1830
2326
  [uploadTask resume];
1831
- lastUploadProgressReportedAt = [[NSDate alloc] init];
1832
2327
  }
1833
2328
  } @catch (NSException *exception) {
1834
2329
  DLog(identifier, @"[RNBackgroundDownloader] - [upload] error: %@", exception.reason);
@@ -1903,8 +2398,19 @@ RCT_EXPORT_METHOD(resumeUploadTask:(NSString *)id resolver:(RCTPromiseResolveBlo
1903
2398
  if (task != nil) {
1904
2399
  [task cancel];
1905
2400
  [self removeUploadTaskFromMap:task];
2401
+ } else {
2402
+ // A config restored after a relaunch with no live task: remove it, or it's
2403
+ // listed by getExistingUploadTasks on every launch
2404
+ for (NSNumber *key in [uploadTaskToConfigMap allKeys]) {
2405
+ RNBGDUploadTaskConfig *config = uploadTaskToConfigMap[key];
2406
+ if ([config.id isEqualToString:identifier]) {
2407
+ [uploadTaskToConfigMap removeObjectForKey:key];
2408
+ }
2409
+ }
2410
+ [mmkv setData:[self serializeUploadConfig:uploadTaskToConfigMap] forKey:ID_TO_UPLOAD_CONFIG_MAP_KEY];
1906
2411
  }
1907
2412
  [idsToUploadPauseSet removeObject:identifier];
2413
+ [self removeMultipartTempFileForUploadId:identifier];
1908
2414
  }
1909
2415
  resolve(nil);
1910
2416
  } @catch (NSException *exception) {
@@ -2028,7 +2534,10 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2028
2534
  #endif
2029
2535
  }
2030
2536
 
2031
- // Update progress
2537
+ // Update progress, unless the app has paused the upload
2538
+ if ([idsToUploadPauseSet containsObject:taskConfig.id]) {
2539
+ return;
2540
+ }
2032
2541
  NSNumber *prevPercent = idToUploadPercentMap[taskConfig.id] ?: @0.0;
2033
2542
  NSNumber *prevBytes = idToUploadLastBytesMap[taskConfig.id] ?: @0;
2034
2543
  float currentPercent = totalBytesExpectedToSend > 0 ? (float)totalBytesSent / (float)totalBytesExpectedToSend : 0.0;
@@ -2083,6 +2592,20 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2083
2592
  }
2084
2593
 
2085
2594
  // Handle upload completion (override the existing method to also handle uploads)
2595
+ // Multipart bodies are written to a temp file named after the upload, so it can be
2596
+ // removed once the upload is over without persisting its path
2597
+ - (NSString *)multipartTempPathForUploadId:(NSString *)identifier {
2598
+ NSString *safeId = [identifier stringByReplacingOccurrencesOfString:@"/" withString:@"_"];
2599
+ return [NSTemporaryDirectory() stringByAppendingPathComponent:[NSString stringWithFormat:@"RNBGD-upload-%@.multipart", safeId]];
2600
+ }
2601
+
2602
+ - (void)removeMultipartTempFileForUploadId:(NSString *)identifier {
2603
+ if (identifier == nil) {
2604
+ return;
2605
+ }
2606
+ [[NSFileManager defaultManager] removeItemAtPath:[self multipartTempPathForUploadId:identifier] error:nil];
2607
+ }
2608
+
2086
2609
  - (void)handleUploadCompletion:(NSURLSessionTask *)task error:(NSError *)error {
2087
2610
  @synchronized (sharedLock) {
2088
2611
  RNBGDUploadTaskConfig *taskConfig = [self uploadConfigForTask:task];
@@ -2096,7 +2619,12 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2096
2619
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - upload was paused, ignoring error");
2097
2620
  return;
2098
2621
  }
2622
+ }
2623
+
2624
+ // The upload is over (failed or done); a paused one returned above and keeps its body
2625
+ [self removeMultipartTempFileForUploadId:taskConfig.id];
2099
2626
 
2627
+ if (error) {
2100
2628
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [handleUploadCompletion] error: %@", error);
2101
2629
  #ifdef RCT_NEW_ARCH_ENABLED
2102
2630
  [self safeEmitEvent:@"onUploadFailed" value:@{
@@ -2153,18 +2681,31 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2153
2681
  NSString *sessionIdentifier =
2154
2682
  [bundleIdentifier stringByAppendingString:@".backgrounddownloadtask"];
2155
2683
  if ([sessionIdentifier isEqualToString:identifier]) {
2684
+ // Called on the main queue by the AppDelegate. A handler left from an earlier launch
2685
+ // must still be called, not dropped
2686
+ if (storedCompletionHandler) {
2687
+ CompletionHandler previous = storedCompletionHandler;
2688
+ storedCompletionHandler = nil;
2689
+ previous();
2690
+ }
2156
2691
  storedCompletionHandler = completionHandler;
2692
+ backgroundEventsFinished = NO;
2693
+ if (idsAwaitingCompleteHandler == nil) {
2694
+ idsAwaitingCompleteHandler = [NSMutableSet new];
2695
+ }
2696
+ [idsAwaitingCompleteHandler removeAllObjects];
2157
2697
 
2158
- // Set a timeout to prevent memory leak if JS never calls completeHandler
2159
- // iOS requires the completion handler to be called within 30 seconds
2160
- // Copy the handler to a local variable to avoid retain cycle with static variable
2698
+ // Call it anyway before the background time runs out, e.g. if JS never calls
2699
+ // completeHandler for a task. Copy the handler to avoid a retain cycle with the static
2161
2700
  __block CompletionHandler handlerToCall = completionHandler;
2162
2701
  dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(kCompletionHandlerTimeout * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
2163
2702
  // Check if this is still the same handler (not already called or replaced)
2164
2703
  if (storedCompletionHandler && storedCompletionHandler == handlerToCall) {
2165
2704
  DLogStatic(nil, @"[RNBackgroundDownloader] - [setCompletionHandlerWithIdentifier] timeout - calling completion handler automatically");
2166
- storedCompletionHandler();
2167
2705
  storedCompletionHandler = nil;
2706
+ backgroundEventsFinished = NO;
2707
+ [idsAwaitingCompleteHandler removeAllObjects];
2708
+ handlerToCall();
2168
2709
  }
2169
2710
  handlerToCall = nil; // Release the block reference
2170
2711
  });
@@ -2200,6 +2741,17 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2200
2741
  return NSFileProtectionCompleteUntilFirstUserAuthentication;
2201
2742
  }
2202
2743
 
2744
+ // The destination in the app's current container: its absolute path changes when the app
2745
+ // is updated, its path relative to the container doesn't. nil if it isn't in the container.
2746
+ - (NSString *)currentPathForDestination:(NSString *)destination {
2747
+ NSString *rootPath = [self getRootPathFromPath:destination];
2748
+ NSString *fileRelativePath = [self getRelativeFilePathFromPath:destination];
2749
+ if (rootPath == nil || fileRelativePath == nil) {
2750
+ return nil;
2751
+ }
2752
+ return [rootPath stringByAppendingPathComponent:fileRelativePath];
2753
+ }
2754
+
2203
2755
  - (BOOL)saveFile: (nonnull RNBGDTaskConfig *) taskConfig downloadURL:(nonnull NSURL *)location bytesDownloaded:(int64_t)bytesDownloaded bytesTotal:(int64_t)bytesTotal error:(NSError **)saveError deferred:(BOOL *)deferred {
2204
2756
  DLog(taskConfig.id, @"[RNBackgroundDownloader] - [saveFile]");
2205
2757
  if (deferred) *deferred = NO;
@@ -2207,11 +2759,10 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2207
2759
  // The absolute path may change when the application is restarted.
2208
2760
  // But the relative path remains the same.
2209
2761
  // Relative paths are used to recreate the Absolute path.
2210
- NSString *rootPath = [self getRootPathFromPath:taskConfig.destination];
2211
- NSString *fileRelativePath = [self getRelativeFilePathFromPath:taskConfig.destination];
2762
+ NSString *fileAbsolutePath = [self currentPathForDestination:taskConfig.destination];
2212
2763
 
2213
2764
  // Check for nil paths to prevent crash
2214
- if (rootPath == nil || fileRelativePath == nil) {
2765
+ if (fileAbsolutePath == nil) {
2215
2766
  if (saveError) {
2216
2767
  *saveError = [NSError errorWithDomain:NSURLErrorDomain
2217
2768
  code:NSURLErrorFileDoesNotExist
@@ -2220,7 +2771,6 @@ RCT_EXPORT_METHOD(getExistingUploadTasks:(RCTPromiseResolveBlock)resolve rejecte
2220
2771
  return NO;
2221
2772
  }
2222
2773
 
2223
- NSString *fileAbsolutePath = [rootPath stringByAppendingPathComponent:fileRelativePath];
2224
2774
  NSURL *destinationURL = [NSURL fileURLWithPath:fileAbsolutePath];
2225
2775
 
2226
2776
  NSFileManager *fileManager = [NSFileManager defaultManager];