Skip to content

Commit

Permalink
fix(ios): Improve KVO observer management for download tasks (#112)
Browse files Browse the repository at this point in the history
* fix(ios): Improve KVO observer management for download tasks

* fix: lint

* fix: lint

* fix: indent

* fix

* fix

* fix

* fix: 100

* fix: 100
  • Loading branch information
gronxb authored Feb 17, 2025
1 parent d6f3454 commit eba2b1a
Showing 1 changed file with 33 additions and 10 deletions.
43 changes: 33 additions & 10 deletions packages/react-native/ios/HotUpdater/HotUpdater.mm
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
#import "HotUpdater.h"
#import <React/RCTReloadCommand.h>
#import <SSZipArchive/SSZipArchive.h>
#import <Foundation/NSURLSession.h>

@implementation HotUpdater {
bool hasListeners;
Expand Down Expand Up @@ -162,22 +163,44 @@ - (void)updateBundle:(NSString *)bundleId zipUrl:(NSURL *)zipUrl completion:(voi
}
}];


// Add observer for progress updates
[downloadTask addObserver:self
forKeyPath:@"countOfBytesReceived"
options:NSKeyValueObservingOptionNew
context:nil];
forKeyPath:@"countOfBytesReceived"
options:NSKeyValueObservingOptionNew
context:nil];
[downloadTask addObserver:self
forKeyPath:@"countOfBytesExpectedToReceive"
options:NSKeyValueObservingOptionNew
context:nil];

forKeyPath:@"countOfBytesExpectedToReceive"
options:NSKeyValueObservingOptionNew
context:nil];

__block HotUpdater *weakSelf = self;
[[NSNotificationCenter defaultCenter] addObserverForName:@"NSURLSessionDownloadTaskDidFinishDownloading"
object:downloadTask
queue:[NSOperationQueue mainQueue]
usingBlock:^(NSNotification * _Nonnull note) {
[weakSelf removeObserversForTask:downloadTask];
}];
[downloadTask resume];

}

#pragma mark - Progress Updates


- (void)removeObserversForTask:(NSURLSessionDownloadTask *)task {
@try {
if ([task observationInfo]) {
[task removeObserver:self forKeyPath:@"countOfBytesReceived"];
[task removeObserver:self forKeyPath:@"countOfBytesExpectedToReceive"];
NSLog(@"KVO observers removed successfully for task: %@", task);
}
} @catch (NSException *exception) {
NSLog(@"Failed to remove observers: %@", exception);
}
}


- (void)observeValueForKeyPath:(NSString *)keyPath
ofObject:(id)object
change:(NSDictionary<NSKeyValueChangeKey, id> *)change
Expand All @@ -191,8 +214,8 @@ - (void)observeValueForKeyPath:(NSString *)keyPath
// Get current timestamp
NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970] * 1000; // Convert to milliseconds

// Send event only if 200ms has passed OR progress is 100%
if ((currentTime - self.lastUpdateTime) >= 200 || progress >= 1.0) {
// Send event only if 100ms has passed OR progress is 100%
if ((currentTime - self.lastUpdateTime) >= 100 || progress >= 1.0) {
self.lastUpdateTime = currentTime; // Update last event timestamp

// Send progress to React Native
Expand Down

0 comments on commit eba2b1a

Please sign in to comment.