Skip to content

Commit ed2f1b7

Browse files
authored
Merge pull request itinance#793 from ifsnow/fix/improve-event-callback
Improve implementation related to event callbacks
2 parents 909aefd + c8e704a commit ed2f1b7

File tree

7 files changed

+172
-114
lines changed

7 files changed

+172
-114
lines changed

Downloader.m

+11-7
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,7 @@ @implementation RNFSDownloader
2626
- (NSString *)downloadFile:(RNFSDownloadParams*)params
2727
{
2828
NSString *uuid = nil;
29-
29+
3030
_params = params;
3131

3232
_lastProgressEmitTimestamp = 0;
@@ -68,20 +68,20 @@ - (NSString *)downloadFile:(RNFSDownloadParams*)params
6868
_session = [NSURLSession sessionWithConfiguration:config delegate:self delegateQueue:nil];
6969
_task = [_session downloadTaskWithURL:url];
7070
[_task resume];
71-
71+
7272
return uuid;
7373
}
7474

7575
- (void)URLSession:(NSURLSession *)session downloadTask:(NSURLSessionDownloadTask *)downloadTask didWriteData:(int64_t)bytesWritten totalBytesWritten:(int64_t)totalBytesWritten totalBytesExpectedToWrite:(int64_t)totalBytesExpectedToWrite
7676
{
7777
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse *)downloadTask.response;
78-
if (!_statusCode) {
78+
if (_params.beginCallback && !_statusCode) {
7979
_statusCode = [NSNumber numberWithLong:httpResponse.statusCode];
8080
_contentLength = [NSNumber numberWithLong:httpResponse.expectedContentLength];
8181
return _params.beginCallback(_statusCode, _contentLength, httpResponse.allHeaderFields);
8282
}
8383

84-
if ([_statusCode isEqualToNumber:[NSNumber numberWithInt:200]]) {
84+
if (_params.progressCallback && [_statusCode isEqualToNumber:[NSNumber numberWithInt:200]]) {
8585
_bytesWritten = @(totalBytesWritten);
8686

8787
if(_params.progressInterval.integerValue > 0){
@@ -136,7 +136,9 @@ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didComp
136136
if (error && error.code != NSURLErrorCancelled) {
137137
_resumeData = error.userInfo[NSURLSessionDownloadTaskResumeData];
138138
if (_resumeData != nil) {
139-
_params.resumableCallback();
139+
if (_params.resumableCallback) {
140+
_params.resumableCallback();
141+
}
140142
} else {
141143
_params.errorCallback(error);
142144
}
@@ -149,14 +151,16 @@ - (void)stopDownload
149151
[_task cancelByProducingResumeData:^(NSData * _Nullable resumeData) {
150152
if (resumeData != nil) {
151153
self.resumeData = resumeData;
152-
self->_params.resumableCallback();
154+
if (self->_params.resumableCallback) {
155+
self->_params.resumableCallback();
156+
}
153157
} else {
154158
NSError *error = [NSError errorWithDomain:@"RNFS"
155159
code:0 //used to pass an NSString @"Aborted" here, but it needs an NSInteger
156160
userInfo:@{
157161
NSLocalizedDescriptionKey: @"Download has been aborted"
158162
}];
159-
163+
160164
self->_params.errorCallback(error);
161165
}
162166
}];

FS.common.js

+22-12
Original file line numberDiff line numberDiff line change
@@ -499,11 +499,17 @@ var RNFS = {
499499
var jobId = getJobId();
500500
var subscriptions = [];
501501

502-
subscriptions.push(RNFS_NativeEventEmitter.addListener('DownloadBegin', options.begin || function() {}));
502+
if (options.begin) {
503+
subscriptions.push(RNFS_NativeEventEmitter.addListener('DownloadBegin', options.begin));
504+
}
503505

504-
subscriptions.push(RNFS_NativeEventEmitter.addListener('DownloadProgress', options.progress || function() {}));
506+
if (options.progress) {
507+
subscriptions.push(RNFS_NativeEventEmitter.addListener('DownloadProgress', options.progress));
508+
}
505509

506-
subscriptions.push(RNFS_NativeEventEmitter.addListener('DownloadResumable', options.resumable || function() {}));
510+
if (options.resumable) {
511+
subscriptions.push(RNFS_NativeEventEmitter.addListener('DownloadResumable', options.resumable));
512+
}
507513

508514
var bridgeOptions = {
509515
jobId: jobId,
@@ -515,7 +521,10 @@ var RNFS = {
515521
progressInterval: options.progressInterval || 0,
516522
readTimeout: options.readTimeout || 15000,
517523
connectionTimeout: options.connectionTimeout || 5000,
518-
backgroundTimeout: options.backgroundTimeout || 3600000 // 1 hour
524+
backgroundTimeout: options.backgroundTimeout || 3600000, // 1 hour
525+
hasBeginCallback: options.begin instanceof Function,
526+
hasProgressCallback: options.progress instanceof Function,
527+
hasResumableCallback: options.resumable instanceof Function,
519528
};
520529

521530
return {
@@ -548,17 +557,16 @@ var RNFS = {
548557
if (options.fields && typeof options.fields !== 'object') throw new Error('uploadFiles: Invalid value for property `fields`');
549558
if (options.method && typeof options.method !== 'string') throw new Error('uploadFiles: Invalid value for property `method`');
550559

551-
552-
subscriptions.push(RNFS_NativeEventEmitter.addListener('UploadBegin', options.begin || function() {}));
553-
554-
if (options.beginCallback && options.beginCallback instanceof Function) {
560+
if (options.begin) {
561+
subscriptions.push(RNFS_NativeEventEmitter.addListener('UploadBegin', options.begin));
562+
} else if (options.beginCallback) {
555563
// Deprecated
556564
subscriptions.push(RNFS_NativeEventEmitter.addListener('UploadBegin', options.beginCallback));
557565
}
558566

559-
subscriptions.push(RNFS_NativeEventEmitter.addListener('UploadProgress', options.progress || function() {}));
560-
561-
if (options.progressCallback && options.progressCallback instanceof Function) {
567+
if (options.progress) {
568+
subscriptions.push(RNFS_NativeEventEmitter.addListener('UploadProgress', options.progress));
569+
} else if (options.progressCallback) {
562570
// Deprecated
563571
subscriptions.push(RNFS_NativeEventEmitter.addListener('UploadProgress', options.progressCallback));
564572
}
@@ -570,7 +578,9 @@ var RNFS = {
570578
binaryStreamOnly: options.binaryStreamOnly || false,
571579
headers: options.headers || {},
572580
fields: options.fields || {},
573-
method: options.method || 'POST'
581+
method: options.method || 'POST',
582+
hasBeginCallback: options.begin instanceof Function || options.beginCallback instanceof Function,
583+
hasProgressCallback: options.progress instanceof Function || options.progressCallback instanceof Function,
574584
};
575585

576586
return {

RNFSManager.m

+47-33
Original file line numberDiff line numberDiff line change
@@ -487,6 +487,9 @@ + (BOOL)requiresMainQueueSetup
487487
params.readTimeout = readTimeout;
488488
NSNumber* backgroundTimeout = options[@"backgroundTimeout"];
489489
params.backgroundTimeout = backgroundTimeout;
490+
bool hasBeginCallback = [options[@"hasBeginCallback"] boolValue];
491+
bool hasProgressCallback = [options[@"hasProgressCallback"] boolValue];
492+
bool hasResumableCallback = [options[@"hasResumableCallback"] boolValue];
490493

491494
__block BOOL callbackFired = NO;
492495

@@ -514,26 +517,32 @@ + (BOOL)requiresMainQueueSetup
514517
return [self reject:reject withError:error];
515518
};
516519

517-
params.beginCallback = ^(NSNumber* statusCode, NSNumber* contentLength, NSDictionary* headers) {
518-
if (self.bridge != nil)
519-
[self sendEventWithName:@"DownloadBegin" body:@{@"jobId": jobId,
520-
@"statusCode": statusCode,
521-
@"contentLength": contentLength,
522-
@"headers": headers ?: [NSNull null]}];
523-
};
520+
if (hasBeginCallback) {
521+
params.beginCallback = ^(NSNumber* statusCode, NSNumber* contentLength, NSDictionary* headers) {
522+
if (self.bridge != nil)
523+
[self sendEventWithName:@"DownloadBegin" body:@{@"jobId": jobId,
524+
@"statusCode": statusCode,
525+
@"contentLength": contentLength,
526+
@"headers": headers ?: [NSNull null]}];
527+
};
528+
}
524529

525-
params.progressCallback = ^(NSNumber* contentLength, NSNumber* bytesWritten) {
526-
if (self.bridge != nil)
527-
[self sendEventWithName:@"DownloadProgress"
528-
body:@{@"jobId": jobId,
529-
@"contentLength": contentLength,
530-
@"bytesWritten": bytesWritten}];
531-
};
532-
530+
if (hasProgressCallback) {
531+
params.progressCallback = ^(NSNumber* contentLength, NSNumber* bytesWritten) {
532+
if (self.bridge != nil)
533+
[self sendEventWithName:@"DownloadProgress"
534+
body:@{@"jobId": jobId,
535+
@"contentLength": contentLength,
536+
@"bytesWritten": bytesWritten}];
537+
};
538+
}
539+
540+
if (hasResumableCallback) {
533541
params.resumableCallback = ^() {
534542
if (self.bridge != nil)
535543
[self sendEventWithName:@"DownloadResumable" body:nil];
536544
};
545+
}
537546

538547
if (!self.downloaders) self.downloaders = [[NSMutableDictionary alloc] init];
539548

@@ -560,7 +569,7 @@ + (BOOL)requiresMainQueueSetup
560569
RCT_EXPORT_METHOD(resumeDownload:(nonnull NSNumber *)jobId)
561570
{
562571
RNFSDownloader* downloader = [self.downloaders objectForKey:[jobId stringValue]];
563-
572+
564573
if (downloader != nil) {
565574
[downloader resumeDownload];
566575
}
@@ -572,7 +581,7 @@ + (BOOL)requiresMainQueueSetup
572581
)
573582
{
574583
RNFSDownloader* downloader = [self.downloaders objectForKey:[jobId stringValue]];
575-
584+
576585
if (downloader != nil) {
577586
resolve([NSNumber numberWithBool:[downloader isResumable]]);
578587
} else {
@@ -605,13 +614,14 @@ + (BOOL)requiresMainQueueSetup
605614
params.toUrl = options[@"toUrl"];
606615
params.files = options[@"files"];
607616
params.binaryStreamOnly = [[options objectForKey:@"binaryStreamOnly"] boolValue];
608-
609617
NSDictionary* headers = options[@"headers"];
610618
NSDictionary* fields = options[@"fields"];
611619
NSString* method = options[@"method"];
612620
params.headers = headers;
613621
params.fields = fields;
614622
params.method = method;
623+
bool hasBeginCallback = [options[@"hasBeginCallback"] boolValue];
624+
bool hasProgressCallback = [options[@"hasProgressCallback"] boolValue];
615625

616626
params.completeCallback = ^(NSString* body, NSURLResponse *resp) {
617627
[self.uploaders removeObjectForKey:[jobId stringValue]];
@@ -630,19 +640,23 @@ + (BOOL)requiresMainQueueSetup
630640
return [self reject:reject withError:error];
631641
};
632642

633-
params.beginCallback = ^() {
634-
if (self.bridge != nil)
635-
[self sendEventWithName:@"UploadBegin"
636-
body:@{@"jobId": jobId}];
637-
};
643+
if (hasBeginCallback) {
644+
params.beginCallback = ^() {
645+
if (self.bridge != nil)
646+
[self sendEventWithName:@"UploadBegin"
647+
body:@{@"jobId": jobId}];
648+
};
649+
}
638650

639-
params.progressCallback = ^(NSNumber* totalBytesExpectedToSend, NSNumber* totalBytesSent) {
640-
if (self.bridge != nil)
641-
[self sendEventWithName:@"UploadProgress"
642-
body:@{@"jobId": jobId,
643-
@"totalBytesExpectedToSend": totalBytesExpectedToSend,
644-
@"totalBytesSent": totalBytesSent}];
645-
};
651+
if (hasProgressCallback) {
652+
params.progressCallback = ^(NSNumber* totalBytesExpectedToSend, NSNumber* totalBytesSent) {
653+
if (self.bridge != nil)
654+
[self sendEventWithName:@"UploadProgress"
655+
body:@{@"jobId": jobId,
656+
@"totalBytesExpectedToSend": totalBytesExpectedToSend,
657+
@"totalBytesSent": totalBytesSent}];
658+
};
659+
}
646660

647661
if (!self.uploaders) self.uploaders = [[NSMutableDictionary alloc] init];
648662

@@ -840,15 +854,15 @@ + (BOOL)requiresMainQueueSetup
840854
//unused?
841855
//__block NSURL* videoURL = [NSURL URLWithString:destination];
842856
__block NSError *error = nil;
843-
857+
844858
PHFetchResult *phAssetFetchResult = [PHAsset fetchAssetsWithALAssetURLs:@[url] options:nil];
845859
PHAsset *phAsset = [phAssetFetchResult firstObject];
846-
860+
847861
PHVideoRequestOptions *options = [[PHVideoRequestOptions alloc] init];
848862
options.networkAccessAllowed = YES;
849863
options.version = PHVideoRequestOptionsVersionOriginal;
850864
options.deliveryMode = PHVideoRequestOptionsDeliveryModeAutomatic;
851-
865+
852866
dispatch_group_t group = dispatch_group_create();
853867
dispatch_group_enter(group);
854868

Uploader.m

+7-3
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,7 @@ - (void)uploadFiles:(RNFSUploadParams*)params
8686
}
8787
[reqBody appendData:[[NSString stringWithFormat:@"Content-Length: %ld\r\n\r\n", (long)[fileData length]] dataUsingEncoding:NSUTF8StringEncoding]];
8888
}
89-
89+
9090
[reqBody appendData:fileData];
9191
if (!binaryStreamOnly) {
9292
[reqBody appendData:[@"\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
@@ -109,7 +109,9 @@ - (void)uploadFiles:(RNFSUploadParams*)params
109109
return self->_params.completeCallback(str, response);
110110
}];
111111
[_task resume];
112-
_params.beginCallback();
112+
if (_params.beginCallback) {
113+
_params.beginCallback();
114+
}
113115
}
114116

115117
- (NSString *)generateBoundaryString
@@ -139,7 +141,9 @@ - (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didComp
139141

140142
- (void)URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesSent totalBytesExpectedToSend:(NSInteger)totalBytesExpectedToSend
141143
{
142-
return _params.progressCallback([NSNumber numberWithLongLong:totalBytesExpectedToSend], [NSNumber numberWithLongLong:totalBytesSent]);
144+
if (_params.progressCallback) {
145+
_params.progressCallback([NSNumber numberWithLongLong:totalBytesExpectedToSend], [NSNumber numberWithLongLong:totalBytesSent]);
146+
}
143147
}
144148

145149
- (void)stopUpload

android/src/main/java/com/rnfs/Downloader.java

+25-16
Original file line numberDiff line numberDiff line change
@@ -97,7 +97,9 @@ private void download(DownloadParams param, DownloadResult res) throws Exception
9797
}
9898
}
9999

100-
mParam.onDownloadBegin.onDownloadBegin(statusCode, lengthOfFile, headersFlat);
100+
if (mParam.onDownloadBegin != null) {
101+
mParam.onDownloadBegin.onDownloadBegin(statusCode, lengthOfFile, headersFlat);
102+
}
101103

102104
input = new BufferedInputStream(connection.getInputStream(), 8 * 1024);
103105
output = new FileOutputStream(param.dest);
@@ -107,29 +109,34 @@ private void download(DownloadParams param, DownloadResult res) throws Exception
107109
int count;
108110
double lastProgressValue = 0;
109111
long lastProgressEmitTimestamp = 0;
112+
boolean hasProgressCallback = mParam.onDownloadProgress != null;
110113

111114
while ((count = input.read(data)) != -1) {
112115
if (mAbort.get()) throw new Exception("Download has been aborted");
113116

114117
total += count;
115-
if (param.progressInterval > 0) {
116-
long timestamp = System.currentTimeMillis();
117-
if (timestamp - lastProgressEmitTimestamp > param.progressInterval) {
118-
lastProgressEmitTimestamp = timestamp;
119-
publishProgress(new long[]{lengthOfFile, total});
120-
}
121-
} else if (param.progressDivider <= 0) {
122-
publishProgress(new long[]{lengthOfFile, total});
123-
} else {
124-
double progress = Math.round(((double) total * 100) / lengthOfFile);
125-
if (progress % param.progressDivider == 0) {
126-
if ((progress != lastProgressValue) || (total == lengthOfFile)) {
127-
Log.d("Downloader", "EMIT: " + String.valueOf(progress) + ", TOTAL:" + String.valueOf(total));
128-
lastProgressValue = progress;
118+
119+
if (hasProgressCallback) {
120+
if (param.progressInterval > 0) {
121+
long timestamp = System.currentTimeMillis();
122+
if (timestamp - lastProgressEmitTimestamp > param.progressInterval) {
123+
lastProgressEmitTimestamp = timestamp;
129124
publishProgress(new long[]{lengthOfFile, total});
130125
}
126+
} else if (param.progressDivider <= 0) {
127+
publishProgress(new long[]{lengthOfFile, total});
128+
} else {
129+
double progress = Math.round(((double) total * 100) / lengthOfFile);
130+
if (progress % param.progressDivider == 0) {
131+
if ((progress != lastProgressValue) || (total == lengthOfFile)) {
132+
Log.d("Downloader", "EMIT: " + String.valueOf(progress) + ", TOTAL:" + String.valueOf(total));
133+
lastProgressValue = progress;
134+
publishProgress(new long[]{lengthOfFile, total});
135+
}
136+
}
131137
}
132138
}
139+
133140
output.write(data, 0, count);
134141
}
135142

@@ -158,7 +165,9 @@ protected void stop() {
158165
@Override
159166
protected void onProgressUpdate(long[]... values) {
160167
super.onProgressUpdate(values);
161-
mParam.onDownloadProgress.onDownloadProgress(values[0][0], values[0][1]);
168+
if (mParam.onDownloadProgress != null) {
169+
mParam.onDownloadProgress.onDownloadProgress(values[0][0], values[0][1]);
170+
}
162171
}
163172

164173
protected void onPostExecute(Exception ex) {

0 commit comments

Comments
 (0)