Bladeren bron

make request timeout consistent with iOS, do not mess with ios indicator if not requested to

Cristiano Coelho 5 jaren geleden
bovenliggende
commit
f2ac3e0b3b
2 gewijzigde bestanden met toevoegingen van 66 en 63 verwijderingen
  1. 1
    1
      android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java
  2. 65
    62
      ios/RNFetchBlobRequest.m

+ 1
- 1
android/src/main/java/com/RNFetchBlob/RNFetchBlobReq.java Bestand weergeven

462
                     // check if this error caused by socket timeout
462
                     // check if this error caused by socket timeout
463
                     if(e.getClass().equals(SocketTimeoutException.class)) {
463
                     if(e.getClass().equals(SocketTimeoutException.class)) {
464
                         respInfo.putBoolean("timeout", true);
464
                         respInfo.putBoolean("timeout", true);
465
-                        callback.invoke("request timed out.", null, null);
465
+                        callback.invoke("The request timed out.", null, null);
466
                     }
466
                     }
467
                     else
467
                     else
468
                         callback.invoke(e.getLocalizedMessage(), null, null);
468
                         callback.invoke(e.getLocalizedMessage(), null, null);

+ 65
- 62
ios/RNFetchBlobRequest.m Bestand weergeven

56
     const char* str = [input UTF8String];
56
     const char* str = [input UTF8String];
57
     unsigned char result[CC_MD5_DIGEST_LENGTH];
57
     unsigned char result[CC_MD5_DIGEST_LENGTH];
58
     CC_MD5(str, (CC_LONG)strlen(str), result);
58
     CC_MD5(str, (CC_LONG)strlen(str), result);
59
-    
59
+
60
     NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
60
     NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
61
     for (int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
61
     for (int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
62
         [ret appendFormat:@"%02x",result[i]];
62
         [ret appendFormat:@"%02x",result[i]];
80
     self.expectedBytes = 0;
80
     self.expectedBytes = 0;
81
     self.receivedBytes = 0;
81
     self.receivedBytes = 0;
82
     self.options = options;
82
     self.options = options;
83
-    
83
+
84
     backgroundTask = [[options valueForKey:@"IOSBackgroundTask"] boolValue];
84
     backgroundTask = [[options valueForKey:@"IOSBackgroundTask"] boolValue];
85
     // when followRedirect not set in options, defaults to TRUE
85
     // when followRedirect not set in options, defaults to TRUE
86
     followRedirect = [options valueForKey:@"followRedirect"] == nil ? YES : [[options valueForKey:@"followRedirect"] boolValue];
86
     followRedirect = [options valueForKey:@"followRedirect"] == nil ? YES : [[options valueForKey:@"followRedirect"] boolValue];
87
     isIncrement = [[options valueForKey:@"increment"] boolValue];
87
     isIncrement = [[options valueForKey:@"increment"] boolValue];
88
     redirects = [[NSMutableArray alloc] init];
88
     redirects = [[NSMutableArray alloc] init];
89
-    
89
+
90
     if (req.URL) {
90
     if (req.URL) {
91
         [redirects addObject:req.URL.absoluteString];
91
         [redirects addObject:req.URL.absoluteString];
92
     }
92
     }
93
-    
93
+
94
     // set response format
94
     // set response format
95
     NSString * rnfbResp = [req.allHTTPHeaderFields valueForKey:@"RNFB-Response"];
95
     NSString * rnfbResp = [req.allHTTPHeaderFields valueForKey:@"RNFB-Response"];
96
-    
96
+
97
     if ([[rnfbResp lowercaseString] isEqualToString:@"base64"]) {
97
     if ([[rnfbResp lowercaseString] isEqualToString:@"base64"]) {
98
         responseFormat = BASE64;
98
         responseFormat = BASE64;
99
     } else if ([[rnfbResp lowercaseString] isEqualToString:@"utf8"]) {
99
     } else if ([[rnfbResp lowercaseString] isEqualToString:@"utf8"]) {
101
     } else {
101
     } else {
102
         responseFormat = AUTO;
102
         responseFormat = AUTO;
103
     }
103
     }
104
-    
104
+
105
     NSString * path = [self.options valueForKey:CONFIG_FILE_PATH];
105
     NSString * path = [self.options valueForKey:CONFIG_FILE_PATH];
106
     NSString * key = [self.options valueForKey:CONFIG_KEY];
106
     NSString * key = [self.options valueForKey:CONFIG_KEY];
107
     NSURLSession * session;
107
     NSURLSession * session;
108
-    
108
+
109
     bodyLength = contentLength;
109
     bodyLength = contentLength;
110
-    
110
+
111
     // the session trust any SSL certification
111
     // the session trust any SSL certification
112
     NSURLSessionConfiguration *defaultConfigObject;
112
     NSURLSessionConfiguration *defaultConfigObject;
113
-    
113
+
114
     defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
114
     defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
115
-    
115
+
116
     if (backgroundTask) {
116
     if (backgroundTask) {
117
         defaultConfigObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:taskId];
117
         defaultConfigObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:taskId];
118
     }
118
     }
119
-    
119
+
120
     // request timeout, -1 if not set in options
120
     // request timeout, -1 if not set in options
121
     float timeout = [options valueForKey:@"timeout"] == nil ? -1 : [[options valueForKey:@"timeout"] floatValue];
121
     float timeout = [options valueForKey:@"timeout"] == nil ? -1 : [[options valueForKey:@"timeout"] floatValue];
122
-    
122
+
123
     if (timeout > 0) {
123
     if (timeout > 0) {
124
         defaultConfigObject.timeoutIntervalForRequest = timeout/1000;
124
         defaultConfigObject.timeoutIntervalForRequest = timeout/1000;
125
     }
125
     }
126
-    
126
+
127
     if([options valueForKey:CONFIG_WIFI_ONLY] != nil && ![options[CONFIG_WIFI_ONLY] boolValue]){
127
     if([options valueForKey:CONFIG_WIFI_ONLY] != nil && ![options[CONFIG_WIFI_ONLY] boolValue]){
128
         [defaultConfigObject setAllowsCellularAccess:NO];
128
         [defaultConfigObject setAllowsCellularAccess:NO];
129
     }
129
     }
130
-    
130
+
131
     defaultConfigObject.HTTPMaximumConnectionsPerHost = 10;
131
     defaultConfigObject.HTTPMaximumConnectionsPerHost = 10;
132
     session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:operationQueue];
132
     session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:operationQueue];
133
-    
133
+
134
     if (path || [self.options valueForKey:CONFIG_USE_TEMP]) {
134
     if (path || [self.options valueForKey:CONFIG_USE_TEMP]) {
135
         respFile = YES;
135
         respFile = YES;
136
-        
136
+
137
         NSString* cacheKey = taskId;
137
         NSString* cacheKey = taskId;
138
         if (key) {
138
         if (key) {
139
             cacheKey = [self md5:key];
139
             cacheKey = [self md5:key];
140
-            
140
+
141
             if (!cacheKey) {
141
             if (!cacheKey) {
142
                 cacheKey = taskId;
142
                 cacheKey = taskId;
143
             }
143
             }
144
-            
144
+
145
             destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
145
             destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
146
-            
146
+
147
             if ([[NSFileManager defaultManager] fileExistsAtPath:destPath]) {
147
             if ([[NSFileManager defaultManager] fileExistsAtPath:destPath]) {
148
                 callback(@[[NSNull null], RESP_TYPE_PATH, destPath]);
148
                 callback(@[[NSNull null], RESP_TYPE_PATH, destPath]);
149
-                
149
+
150
                 return;
150
                 return;
151
             }
151
             }
152
         }
152
         }
153
-        
153
+
154
         if (path) {
154
         if (path) {
155
             destPath = path;
155
             destPath = path;
156
         } else {
156
         } else {
160
         respData = [[NSMutableData alloc] init];
160
         respData = [[NSMutableData alloc] init];
161
         respFile = NO;
161
         respFile = NO;
162
     }
162
     }
163
-    
163
+
164
     self.task = [session dataTaskWithRequest:req];
164
     self.task = [session dataTaskWithRequest:req];
165
     [self.task resume];
165
     [self.task resume];
166
-    
166
+
167
     // network status indicator
167
     // network status indicator
168
     if ([[options objectForKey:CONFIG_INDICATOR] boolValue]) {
168
     if ([[options objectForKey:CONFIG_INDICATOR] boolValue]) {
169
         dispatch_async(dispatch_get_main_queue(), ^{
169
         dispatch_async(dispatch_get_main_queue(), ^{
187
 - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
187
 - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
188
 {
188
 {
189
     expectedBytes = [response expectedContentLength];
189
     expectedBytes = [response expectedContentLength];
190
-    
190
+
191
     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
191
     NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
192
     NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
192
     NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
193
     NSString * respType = @"";
193
     NSString * respType = @"";
194
     respStatus = statusCode;
194
     respStatus = statusCode;
195
-    
195
+
196
     if ([response respondsToSelector:@selector(allHeaderFields)])
196
     if ([response respondsToSelector:@selector(allHeaderFields)])
197
     {
197
     {
198
         NSDictionary *headers = [httpResponse allHeaderFields];
198
         NSDictionary *headers = [httpResponse allHeaderFields];
199
         NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
199
         NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
200
-        
200
+
201
         if (self.isServerPush) {
201
         if (self.isServerPush) {
202
             if (partBuffer) {
202
             if (partBuffer) {
203
                 [self.bridge.eventDispatcher
203
                 [self.bridge.eventDispatcher
208
                         }
208
                         }
209
                  ];
209
                  ];
210
             }
210
             }
211
-            
211
+
212
             partBuffer = [[NSMutableData alloc] init];
212
             partBuffer = [[NSMutableData alloc] init];
213
             completionHandler(NSURLSessionResponseAllow);
213
             completionHandler(NSURLSessionResponseAllow);
214
 
214
 
216
         } else {
216
         } else {
217
             self.isServerPush = [[respCType lowercaseString] RNFBContainsString:@"multipart/x-mixed-replace;"];
217
             self.isServerPush = [[respCType lowercaseString] RNFBContainsString:@"multipart/x-mixed-replace;"];
218
         }
218
         }
219
-        
219
+
220
         if(respCType)
220
         if(respCType)
221
         {
221
         {
222
             NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
222
             NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
223
-            
223
+
224
             if ([respCType RNFBContainsString:@"text/"]) {
224
             if ([respCType RNFBContainsString:@"text/"]) {
225
                 respType = @"text";
225
                 respType = @"text";
226
             } else if ([respCType RNFBContainsString:@"application/json"]) {
226
             } else if ([respCType RNFBContainsString:@"application/json"]) {
236
                 }
236
                 }
237
             } else {
237
             } else {
238
                 respType = @"blob";
238
                 respType = @"blob";
239
-                
239
+
240
                 // for XMLHttpRequest, switch response data handling strategy automatically
240
                 // for XMLHttpRequest, switch response data handling strategy automatically
241
                 if ([options valueForKey:@"auto"]) {
241
                 if ([options valueForKey:@"auto"]) {
242
                     respFile = YES;
242
                     respFile = YES;
246
         } else {
246
         } else {
247
             respType = @"text";
247
             respType = @"text";
248
         }
248
         }
249
-        
249
+
250
 #pragma mark - handling cookies
250
 #pragma mark - handling cookies
251
         // # 153 get cookies
251
         // # 153 get cookies
252
         if (response.URL) {
252
         if (response.URL) {
256
                 [cookieStore setCookies:cookies forURL:response.URL mainDocumentURL:nil];
256
                 [cookieStore setCookies:cookies forURL:response.URL mainDocumentURL:nil];
257
             }
257
             }
258
         }
258
         }
259
-        
259
+
260
         [self.bridge.eventDispatcher
260
         [self.bridge.eventDispatcher
261
          sendDeviceEventWithName: EVENT_STATE_CHANGE
261
          sendDeviceEventWithName: EVENT_STATE_CHANGE
262
          body:@{
262
          body:@{
272
     } else {
272
     } else {
273
         NSLog(@"oops");
273
         NSLog(@"oops");
274
     }
274
     }
275
-    
275
+
276
     if (respFile)
276
     if (respFile)
277
     {
277
     {
278
         @try{
278
         @try{
279
             NSFileManager * fm = [NSFileManager defaultManager];
279
             NSFileManager * fm = [NSFileManager defaultManager];
280
             NSString * folder = [destPath stringByDeletingLastPathComponent];
280
             NSString * folder = [destPath stringByDeletingLastPathComponent];
281
-            
281
+
282
             if (![fm fileExistsAtPath:folder]) {
282
             if (![fm fileExistsAtPath:folder]) {
283
                 [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
283
                 [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
284
             }
284
             }
285
-            
285
+
286
             // if not set overwrite in options, defaults to TRUE
286
             // if not set overwrite in options, defaults to TRUE
287
             BOOL overwrite = [options valueForKey:@"overwrite"] == nil ? YES : [[options valueForKey:@"overwrite"] boolValue];
287
             BOOL overwrite = [options valueForKey:@"overwrite"] == nil ? YES : [[options valueForKey:@"overwrite"] boolValue];
288
             BOOL appendToExistingFile = [destPath RNFBContainsString:@"?append=true"];
288
             BOOL appendToExistingFile = [destPath RNFBContainsString:@"?append=true"];
289
-            
289
+
290
             appendToExistingFile = !overwrite;
290
             appendToExistingFile = !overwrite;
291
-            
291
+
292
             // For solving #141 append response data if the file already exists
292
             // For solving #141 append response data if the file already exists
293
             // base on PR#139 @kejinliang
293
             // base on PR#139 @kejinliang
294
             if (appendToExistingFile) {
294
             if (appendToExistingFile) {
295
                 destPath = [destPath stringByReplacingOccurrencesOfString:@"?append=true" withString:@""];
295
                 destPath = [destPath stringByReplacingOccurrencesOfString:@"?append=true" withString:@""];
296
             }
296
             }
297
-            
297
+
298
             if (![fm fileExistsAtPath:destPath]) {
298
             if (![fm fileExistsAtPath:destPath]) {
299
                 [fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
299
                 [fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
300
             }
300
             }
301
-            
301
+
302
             writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:appendToExistingFile];
302
             writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:appendToExistingFile];
303
             [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
303
             [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
304
             [writeStream open];
304
             [writeStream open];
308
             NSLog(@"write file error");
308
             NSLog(@"write file error");
309
         }
309
         }
310
     }
310
     }
311
-    
311
+
312
     completionHandler(NSURLSessionResponseAllow);
312
     completionHandler(NSURLSessionResponseAllow);
313
 }
313
 }
314
 
314
 
320
     if (self.isServerPush)
320
     if (self.isServerPush)
321
     {
321
     {
322
         [partBuffer appendData:data];
322
         [partBuffer appendData:data];
323
-        
323
+
324
         return ;
324
         return ;
325
     }
325
     }
326
-    
326
+
327
     NSNumber * received = [NSNumber numberWithLong:[data length]];
327
     NSNumber * received = [NSNumber numberWithLong:[data length]];
328
     receivedBytes += [received longValue];
328
     receivedBytes += [received longValue];
329
     NSString * chunkString = @"";
329
     NSString * chunkString = @"";
330
-    
330
+
331
     if (isIncrement) {
331
     if (isIncrement) {
332
         chunkString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
332
         chunkString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
333
     }
333
     }
334
-    
334
+
335
     if (respFile) {
335
     if (respFile) {
336
         [writeStream write:[data bytes] maxLength:[data length]];
336
         [writeStream write:[data bytes] maxLength:[data length]];
337
     } else {
337
     } else {
338
         [respData appendData:data];
338
         [respData appendData:data];
339
     }
339
     }
340
-    
340
+
341
     if (expectedBytes == 0) {
341
     if (expectedBytes == 0) {
342
         return;
342
         return;
343
     }
343
     }
344
-    
344
+
345
     NSNumber * now =[NSNumber numberWithFloat:((float)receivedBytes/(float)expectedBytes)];
345
     NSNumber * now =[NSNumber numberWithFloat:((float)receivedBytes/(float)expectedBytes)];
346
-    
346
+
347
     if ([self.progressConfig shouldReport:now]) {
347
     if ([self.progressConfig shouldReport:now]) {
348
         [self.bridge.eventDispatcher
348
         [self.bridge.eventDispatcher
349
          sendDeviceEventWithName:EVENT_PROGRESS
349
          sendDeviceEventWithName:EVENT_PROGRESS
367
 
367
 
368
 - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
368
 - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
369
 {
369
 {
370
-    
370
+
371
     self.error = error;
371
     self.error = error;
372
     NSString * errMsg;
372
     NSString * errMsg;
373
     NSString * respStr;
373
     NSString * respStr;
374
     NSString * rnfbRespType;
374
     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
+
380
     if (error) {
383
     if (error) {
381
         if (error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled) {
384
         if (error.domain == NSURLErrorDomain && error.code == NSURLErrorCancelled) {
382
             errMsg = @"task cancelled";
385
             errMsg = @"task cancelled";
384
             errMsg = [error localizedDescription];
387
             errMsg = [error localizedDescription];
385
         }
388
         }
386
     }
389
     }
387
-    
390
+
388
     if (respFile) {
391
     if (respFile) {
389
         [writeStream close];
392
         [writeStream close];
390
         rnfbRespType = RESP_TYPE_PATH;
393
         rnfbRespType = RESP_TYPE_PATH;
395
         // if it turns out not to be `nil` that means the response data contains valid UTF8 string,
398
         // if it turns out not to be `nil` that means the response data contains valid UTF8 string,
396
         // in order to properly encode the UTF8 string, use URL encoding before BASE64 encoding.
399
         // in order to properly encode the UTF8 string, use URL encoding before BASE64 encoding.
397
         NSString * utf8 = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
400
         NSString * utf8 = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
398
-        
401
+
399
         if (responseFormat == BASE64) {
402
         if (responseFormat == BASE64) {
400
             rnfbRespType = RESP_TYPE_BASE64;
403
             rnfbRespType = RESP_TYPE_BASE64;
401
             respStr = [respData base64EncodedStringWithOptions:0];
404
             respStr = [respData base64EncodedStringWithOptions:0];
412
             }
415
             }
413
         }
416
         }
414
     }
417
     }
415
-    
416
-    
418
+
419
+
417
     callback(@[
420
     callback(@[
418
                errMsg ?: [NSNull null],
421
                errMsg ?: [NSNull null],
419
                rnfbRespType ?: @"",
422
                rnfbRespType ?: @"",
420
                respStr ?: [NSNull null]
423
                respStr ?: [NSNull null]
421
                ]);
424
                ]);
422
-    
425
+
423
     respData = nil;
426
     respData = nil;
424
     receivedBytes = 0;
427
     receivedBytes = 0;
425
     [session finishTasksAndInvalidate];
428
     [session finishTasksAndInvalidate];
426
-    
429
+
427
 }
430
 }
428
 
431
 
429
 // upload progress handler
432
 // upload progress handler
432
     if (totalBytesExpectedToWrite == 0) {
435
     if (totalBytesExpectedToWrite == 0) {
433
         return;
436
         return;
434
     }
437
     }
435
-    
438
+
436
     NSNumber * now = [NSNumber numberWithFloat:((float)totalBytesWritten/(float)totalBytesExpectedToWrite)];
439
     NSNumber * now = [NSNumber numberWithFloat:((float)totalBytesWritten/(float)totalBytesExpectedToWrite)];
437
 
440
 
438
     if ([self.uploadProgressConfig shouldReport:now]) {
441
     if ([self.uploadProgressConfig shouldReport:now]) {
465
 
468
 
466
 - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
469
 - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
467
 {
470
 {
468
-    
471
+
469
     if (followRedirect) {
472
     if (followRedirect) {
470
         if (request.URL) {
473
         if (request.URL) {
471
             [redirects addObject:[request.URL absoluteString]];
474
             [redirects addObject:[request.URL absoluteString]];
472
         }
475
         }
473
-        
476
+
474
         completionHandler(request);
477
         completionHandler(request);
475
     } else {
478
     } else {
476
         completionHandler(nil);
479
         completionHandler(nil);