Skip to content

Commit f2ac3e0

Browse files
committed
make request timeout consistent with iOS, do not mess with ios indicator if not requested to
1 parent 92a46a2 commit f2ac3e0

File tree

2 files changed

+66
-63
lines changed

2 files changed

+66
-63
lines changed

android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -462,7 +462,7 @@ public void onFailure(@NonNull Call call, IOException e) {
462462
// check if this error caused by socket timeout
463463
if(e.getClass().equals(SocketTimeoutException.class)) {
464464
respInfo.putBoolean("timeout", true);
465-
callback.invoke("request timed out.", null, null);
465+
callback.invoke("The request timed out.", null, null);
466466
}
467467
else
468468
callback.invoke(e.getLocalizedMessage(), null, null);

ios/RNFetchBlobRequest.m

Lines changed: 65 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,7 @@ - (NSString *)md5:(NSString *)input {
5656
const char* str = [input UTF8String];
5757
unsigned char result[CC_MD5_DIGEST_LENGTH];
5858
CC_MD5(str, (CC_LONG)strlen(str), result);
59-
59+
6060
NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
6161
for (int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
6262
[ret appendFormat:@"%02x",result[i]];
@@ -80,77 +80,77 @@ - (void) sendRequest:(__weak NSDictionary * _Nullable )options
8080
self.expectedBytes = 0;
8181
self.receivedBytes = 0;
8282
self.options = options;
83-
83+
8484
backgroundTask = [[options valueForKey:@"IOSBackgroundTask"] boolValue];
8585
// when followRedirect not set in options, defaults to TRUE
8686
followRedirect = [options valueForKey:@"followRedirect"] == nil ? YES : [[options valueForKey:@"followRedirect"] boolValue];
8787
isIncrement = [[options valueForKey:@"increment"] boolValue];
8888
redirects = [[NSMutableArray alloc] init];
89-
89+
9090
if (req.URL) {
9191
[redirects addObject:req.URL.absoluteString];
9292
}
93-
93+
9494
// set response format
9595
NSString * rnfbResp = [req.allHTTPHeaderFields valueForKey:@"RNFB-Response"];
96-
96+
9797
if ([[rnfbResp lowercaseString] isEqualToString:@"base64"]) {
9898
responseFormat = BASE64;
9999
} else if ([[rnfbResp lowercaseString] isEqualToString:@"utf8"]) {
100100
responseFormat = UTF8;
101101
} else {
102102
responseFormat = AUTO;
103103
}
104-
104+
105105
NSString * path = [self.options valueForKey:CONFIG_FILE_PATH];
106106
NSString * key = [self.options valueForKey:CONFIG_KEY];
107107
NSURLSession * session;
108-
108+
109109
bodyLength = contentLength;
110-
110+
111111
// the session trust any SSL certification
112112
NSURLSessionConfiguration *defaultConfigObject;
113-
113+
114114
defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
115-
115+
116116
if (backgroundTask) {
117117
defaultConfigObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:taskId];
118118
}
119-
119+
120120
// request timeout, -1 if not set in options
121121
float timeout = [options valueForKey:@"timeout"] == nil ? -1 : [[options valueForKey:@"timeout"] floatValue];
122-
122+
123123
if (timeout > 0) {
124124
defaultConfigObject.timeoutIntervalForRequest = timeout/1000;
125125
}
126-
126+
127127
if([options valueForKey:CONFIG_WIFI_ONLY] != nil && ![options[CONFIG_WIFI_ONLY] boolValue]){
128128
[defaultConfigObject setAllowsCellularAccess:NO];
129129
}
130-
130+
131131
defaultConfigObject.HTTPMaximumConnectionsPerHost = 10;
132132
session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:operationQueue];
133-
133+
134134
if (path || [self.options valueForKey:CONFIG_USE_TEMP]) {
135135
respFile = YES;
136-
136+
137137
NSString* cacheKey = taskId;
138138
if (key) {
139139
cacheKey = [self md5:key];
140-
140+
141141
if (!cacheKey) {
142142
cacheKey = taskId;
143143
}
144-
144+
145145
destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
146-
146+
147147
if ([[NSFileManager defaultManager] fileExistsAtPath:destPath]) {
148148
callback(@[[NSNull null], RESP_TYPE_PATH, destPath]);
149-
149+
150150
return;
151151
}
152152
}
153-
153+
154154
if (path) {
155155
destPath = path;
156156
} else {
@@ -160,10 +160,10 @@ - (void) sendRequest:(__weak NSDictionary * _Nullable )options
160160
respData = [[NSMutableData alloc] init];
161161
respFile = NO;
162162
}
163-
163+
164164
self.task = [session dataTaskWithRequest:req];
165165
[self.task resume];
166-
166+
167167
// network status indicator
168168
if ([[options objectForKey:CONFIG_INDICATOR] boolValue]) {
169169
dispatch_async(dispatch_get_main_queue(), ^{
@@ -187,17 +187,17 @@ - (void) sendRequest:(__weak NSDictionary * _Nullable )options
187187
- (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
188188
{
189189
expectedBytes = [response expectedContentLength];
190-
190+
191191
NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
192192
NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
193193
NSString * respType = @"";
194194
respStatus = statusCode;
195-
195+
196196
if ([response respondsToSelector:@selector(allHeaderFields)])
197197
{
198198
NSDictionary *headers = [httpResponse allHeaderFields];
199199
NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
200-
200+
201201
if (self.isServerPush) {
202202
if (partBuffer) {
203203
[self.bridge.eventDispatcher
@@ -208,19 +208,19 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
208208
}
209209
];
210210
}
211-
211+
212212
partBuffer = [[NSMutableData alloc] init];
213213
completionHandler(NSURLSessionResponseAllow);
214214

215215
return;
216216
} else {
217217
self.isServerPush = [[respCType lowercaseString] RNFBContainsString:@"multipart/x-mixed-replace;"];
218218
}
219-
219+
220220
if(respCType)
221221
{
222222
NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
223-
223+
224224
if ([respCType RNFBContainsString:@"text/"]) {
225225
respType = @"text";
226226
} else if ([respCType RNFBContainsString:@"application/json"]) {
@@ -236,7 +236,7 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
236236
}
237237
} else {
238238
respType = @"blob";
239-
239+
240240
// for XMLHttpRequest, switch response data handling strategy automatically
241241
if ([options valueForKey:@"auto"]) {
242242
respFile = YES;
@@ -246,7 +246,7 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
246246
} else {
247247
respType = @"text";
248248
}
249-
249+
250250
#pragma mark - handling cookies
251251
// # 153 get cookies
252252
if (response.URL) {
@@ -256,7 +256,7 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
256256
[cookieStore setCookies:cookies forURL:response.URL mainDocumentURL:nil];
257257
}
258258
}
259-
259+
260260
[self.bridge.eventDispatcher
261261
sendDeviceEventWithName: EVENT_STATE_CHANGE
262262
body:@{
@@ -272,33 +272,33 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
272272
} else {
273273
NSLog(@"oops");
274274
}
275-
275+
276276
if (respFile)
277277
{
278278
@try{
279279
NSFileManager * fm = [NSFileManager defaultManager];
280280
NSString * folder = [destPath stringByDeletingLastPathComponent];
281-
281+
282282
if (![fm fileExistsAtPath:folder]) {
283283
[fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
284284
}
285-
285+
286286
// if not set overwrite in options, defaults to TRUE
287287
BOOL overwrite = [options valueForKey:@"overwrite"] == nil ? YES : [[options valueForKey:@"overwrite"] boolValue];
288288
BOOL appendToExistingFile = [destPath RNFBContainsString:@"?append=true"];
289-
289+
290290
appendToExistingFile = !overwrite;
291-
291+
292292
// For solving #141 append response data if the file already exists
293293
// base on PR#139 @kejinliang
294294
if (appendToExistingFile) {
295295
destPath = [destPath stringByReplacingOccurrencesOfString:@"?append=true" withString:@""];
296296
}
297-
297+
298298
if (![fm fileExistsAtPath:destPath]) {
299299
[fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
300300
}
301-
301+
302302
writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:appendToExistingFile];
303303
[writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
304304
[writeStream open];
@@ -308,7 +308,7 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
308308
NSLog(@"write file error");
309309
}
310310
}
311-
311+
312312
completionHandler(NSURLSessionResponseAllow);
313313
}
314314

@@ -320,30 +320,30 @@ - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dat
320320
if (self.isServerPush)
321321
{
322322
[partBuffer appendData:data];
323-
323+
324324
return ;
325325
}
326-
326+
327327
NSNumber * received = [NSNumber numberWithLong:[data length]];
328328
receivedBytes += [received longValue];
329329
NSString * chunkString = @"";
330-
330+
331331
if (isIncrement) {
332332
chunkString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
333333
}
334-
334+
335335
if (respFile) {
336336
[writeStream write:[data bytes] maxLength:[data length]];
337337
} else {
338338
[respData appendData:data];
339339
}
340-
340+
341341
if (expectedBytes == 0) {
342342
return;
343343
}
344-
344+
345345
NSNumber * now =[NSNumber numberWithFloat:((float)receivedBytes/(float)expectedBytes)];
346-
346+
347347
if ([self.progressConfig shouldReport:now]) {
348348
[self.bridge.eventDispatcher
349349
sendDeviceEventWithName:EVENT_PROGRESS
@@ -367,24 +367,27 @@ - (void) URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable
367367

368368
- (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
369369
{
370-
370+
371371
self.error = error;
372372
NSString * errMsg;
373373
NSString * respStr;
374374
NSString * rnfbRespType;
375-
376-
dispatch_async(dispatch_get_main_queue(), ^{
377-
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
378-
});
379-
375+
376+
// only run this if we were requested to change it
377+
if ([[options objectForKey:CONFIG_INDICATOR] boolValue]) {
378+
dispatch_async(dispatch_get_main_queue(), ^{
379+
[[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
380+
});
381+
}
382+
380383
if (error) {
381384
if (error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled) {
382385
errMsg = @"task cancelled";
383386
} else {
384387
errMsg = [error localizedDescription];
385388
}
386389
}
387-
390+
388391
if (respFile) {
389392
[writeStream close];
390393
rnfbRespType = RESP_TYPE_PATH;
@@ -395,7 +398,7 @@ - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCom
395398
// if it turns out not to be `nil` that means the response data contains valid UTF8 string,
396399
// in order to properly encode the UTF8 string, use URL encoding before BASE64 encoding.
397400
NSString * utf8 = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
398-
401+
399402
if (responseFormat == BASE64) {
400403
rnfbRespType = RESP_TYPE_BASE64;
401404
respStr = [respData base64EncodedStringWithOptions:0];
@@ -412,18 +415,18 @@ - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCom
412415
}
413416
}
414417
}
415-
416-
418+
419+
417420
callback(@[
418421
errMsg ?: [NSNull null],
419422
rnfbRespType ?: @"",
420423
respStr ?: [NSNull null]
421424
]);
422-
425+
423426
respData = nil;
424427
receivedBytes = 0;
425428
[session finishTasksAndInvalidate];
426-
429+
427430
}
428431

429432
// upload progress handler
@@ -432,7 +435,7 @@ - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSen
432435
if (totalBytesExpectedToWrite == 0) {
433436
return;
434437
}
435-
438+
436439
NSNumber * now = [NSNumber numberWithFloat:((float)totalBytesWritten/(float)totalBytesExpectedToWrite)];
437440

438441
if ([self.uploadProgressConfig shouldReport:now]) {
@@ -465,12 +468,12 @@ - (void) URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)sessio
465468

466469
- (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
467470
{
468-
471+
469472
if (followRedirect) {
470473
if (request.URL) {
471474
[redirects addObject:[request.URL absoluteString]];
472475
}
473-
476+
474477
completionHandler(request);
475478
} else {
476479
completionHandler(nil);

0 commit comments

Comments
 (0)