Browse Source

Some code guidelines for network classes

Artur Chrusciel 7 years ago
parent
commit
57102f4d1e
2 changed files with 97 additions and 113 deletions
  1. 5
    5
      ios/RNFetchBlobNetwork.m
  2. 92
    108
      ios/RNFetchBlobRequest.m

+ 5
- 5
ios/RNFetchBlobNetwork.m View File

36
 
36
 
37
 __attribute__((constructor))
37
 __attribute__((constructor))
38
 static void initialize_tables() {
38
 static void initialize_tables() {
39
-    if(expirationTable == nil)
40
-    {
39
+    if (expirationTable == nil) {
41
         expirationTable = [[NSMapTable alloc] init];
40
         expirationTable = [[NSMapTable alloc] init];
42
     }
41
     }
43
 }
42
 }
62
 + (RNFetchBlobNetwork* _Nullable)sharedInstance {
61
 + (RNFetchBlobNetwork* _Nullable)sharedInstance {
63
     static id _sharedInstance = nil;
62
     static id _sharedInstance = nil;
64
     static dispatch_once_t onceToken;
63
     static dispatch_once_t onceToken;
64
+
65
     dispatch_once(&onceToken, ^{
65
     dispatch_once(&onceToken, ^{
66
         _sharedInstance = [[self alloc] init];
66
         _sharedInstance = [[self alloc] init];
67
     });
67
     });
116
         task = [self.requestsTable objectForKey:taskId].task;
116
         task = [self.requestsTable objectForKey:taskId].task;
117
     }
117
     }
118
     
118
     
119
-    if(task && task.state == NSURLSessionTaskStateRunning) {
119
+    if (task && task.state == NSURLSessionTaskStateRunning) {
120
         [task cancel];
120
         [task cancel];
121
     }
121
     }
122
 }
122
 }
125
 + (NSMutableDictionary *) normalizeHeaders:(NSDictionary *)headers
125
 + (NSMutableDictionary *) normalizeHeaders:(NSDictionary *)headers
126
 {
126
 {
127
     NSMutableDictionary * mheaders = [[NSMutableDictionary alloc]init];
127
     NSMutableDictionary * mheaders = [[NSMutableDictionary alloc]init];
128
-    for(NSString * key in headers) {
128
+    for (NSString * key in headers) {
129
         [mheaders setValue:[headers valueForKey:key] forKey:[key lowercaseString]];
129
         [mheaders setValue:[headers valueForKey:key] forKey:[key lowercaseString]];
130
     }
130
     }
131
     
131
     
139
         NSEnumerator * emu =  [expirationTable keyEnumerator];
139
         NSEnumerator * emu =  [expirationTable keyEnumerator];
140
         NSString * key;
140
         NSString * key;
141
         
141
         
142
-        while((key = [emu nextObject]))
142
+        while ((key = [emu nextObject]))
143
         {
143
         {
144
             RCTBridge * bridge = [RNFetchBlob getRCTBridge];
144
             RCTBridge * bridge = [RNFetchBlob getRCTBridge];
145
             id args = @{ @"taskId": key };
145
             id args = @{ @"taskId": key };

+ 92
- 108
ios/RNFetchBlobRequest.m View File

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]];
63
     }
63
     }
64
     return ret;
64
     return ret;
81
     self.receivedBytes = 0;
81
     self.receivedBytes = 0;
82
     self.options = options;
82
     self.options = options;
83
     
83
     
84
-    backgroundTask = [options valueForKey:@"IOSBackgroundTask"] == nil ? NO : [[options valueForKey:@"IOSBackgroundTask"] boolValue];
84
+    backgroundTask = [[options valueForKey:@"IOSBackgroundTask"] boolValue];
85
+    // when followRedirect not set in options, defaults to TRUE
85
     followRedirect = [options valueForKey:@"followRedirect"] == nil ? YES : [[options valueForKey:@"followRedirect"] boolValue];
86
     followRedirect = [options valueForKey:@"followRedirect"] == nil ? YES : [[options valueForKey:@"followRedirect"] boolValue];
86
-    isIncrement = [options valueForKey:@"increment"] == nil ? NO : [[options valueForKey:@"increment"] boolValue];
87
+    isIncrement = [[options valueForKey:@"increment"] boolValue];
87
     redirects = [[NSMutableArray alloc] init];
88
     redirects = [[NSMutableArray alloc] init];
88
-    if(req.URL != nil)
89
+    
90
+    if (req.URL) {
89
         [redirects addObject:req.URL.absoluteString];
91
         [redirects addObject:req.URL.absoluteString];
92
+    }
90
     
93
     
91
     // set response format
94
     // set response format
92
     NSString * rnfbResp = [req.allHTTPHeaderFields valueForKey:@"RNFB-Response"];
95
     NSString * rnfbResp = [req.allHTTPHeaderFields valueForKey:@"RNFB-Response"];
93
-    if([[rnfbResp lowercaseString] isEqualToString:@"base64"])
96
+    
97
+    if ([[rnfbResp lowercaseString] isEqualToString:@"base64"]) {
94
         responseFormat = BASE64;
98
         responseFormat = BASE64;
95
-    else if([[rnfbResp lowercaseString] isEqualToString:@"utf8"])
99
+    } else if ([[rnfbResp lowercaseString] isEqualToString:@"utf8"]) {
96
         responseFormat = UTF8;
100
         responseFormat = UTF8;
97
-    else
101
+    } else {
98
         responseFormat = AUTO;
102
         responseFormat = AUTO;
103
+    }
99
     
104
     
100
     NSString * path = [self.options valueForKey:CONFIG_FILE_PATH];
105
     NSString * path = [self.options valueForKey:CONFIG_FILE_PATH];
101
     NSString * key = [self.options valueForKey:CONFIG_KEY];
106
     NSString * key = [self.options valueForKey:CONFIG_KEY];
108
     
113
     
109
     defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
114
     defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
110
     
115
     
111
-    if(backgroundTask)
112
-    {
116
+    if (backgroundTask) {
113
         defaultConfigObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:taskId];
117
         defaultConfigObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:taskId];
114
     }
118
     }
115
     
119
     
116
-    // set request timeout
120
+    // request timeout, -1 if not set in options
117
     float timeout = [options valueForKey:@"timeout"] == nil ? -1 : [[options valueForKey:@"timeout"] floatValue];
121
     float timeout = [options valueForKey:@"timeout"] == nil ? -1 : [[options valueForKey:@"timeout"] floatValue];
118
-    if(timeout > 0)
119
-    {
122
+    
123
+    if (timeout > 0) {
120
         defaultConfigObject.timeoutIntervalForRequest = timeout/1000;
124
         defaultConfigObject.timeoutIntervalForRequest = timeout/1000;
121
     }
125
     }
126
+    
122
     defaultConfigObject.HTTPMaximumConnectionsPerHost = 10;
127
     defaultConfigObject.HTTPMaximumConnectionsPerHost = 10;
123
     session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:operationQueue];
128
     session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:operationQueue];
124
-    if(path != nil || [self.options valueForKey:CONFIG_USE_TEMP]!= nil)
125
-    {
129
+    
130
+    if (path || [self.options valueForKey:CONFIG_USE_TEMP]) {
126
         respFile = YES;
131
         respFile = YES;
127
         
132
         
128
         NSString* cacheKey = taskId;
133
         NSString* cacheKey = taskId;
129
-        if (key != nil) {
134
+        if (key) {
130
             cacheKey = [self md5:key];
135
             cacheKey = [self md5:key];
131
-            if (cacheKey == nil) {
136
+            
137
+            if (!cacheKey) {
132
                 cacheKey = taskId;
138
                 cacheKey = taskId;
133
             }
139
             }
134
             
140
             
135
             destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
141
             destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
142
+            
136
             if ([[NSFileManager defaultManager] fileExistsAtPath:destPath]) {
143
             if ([[NSFileManager defaultManager] fileExistsAtPath:destPath]) {
137
                 callback(@[[NSNull null], RESP_TYPE_PATH, destPath]);
144
                 callback(@[[NSNull null], RESP_TYPE_PATH, destPath]);
145
+                
138
                 return;
146
                 return;
139
             }
147
             }
140
         }
148
         }
141
         
149
         
142
-        if(path != nil)
150
+        if (path) {
143
             destPath = path;
151
             destPath = path;
144
-        else
152
+        } else {
145
             destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
153
             destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
146
-    }
147
-    else
148
-    {
154
+        }
155
+    } else {
149
         respData = [[NSMutableData alloc] init];
156
         respData = [[NSMutableData alloc] init];
150
         respFile = NO;
157
         respFile = NO;
151
     }
158
     }
154
     [self.task resume];
161
     [self.task resume];
155
     
162
     
156
     // network status indicator
163
     // network status indicator
157
-    if([[options objectForKey:CONFIG_INDICATOR] boolValue] == YES)
164
+    if ([[options objectForKey:CONFIG_INDICATOR] boolValue]) {
158
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
165
         [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
159
-    
166
+    }
160
 }
167
 }
161
 
168
 
162
 ////////////////////////////////////////
169
 ////////////////////////////////////////
179
     NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
186
     NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
180
     NSString * respType = @"";
187
     NSString * respType = @"";
181
     respStatus = statusCode;
188
     respStatus = statusCode;
189
+    
182
     if ([response respondsToSelector:@selector(allHeaderFields)])
190
     if ([response respondsToSelector:@selector(allHeaderFields)])
183
     {
191
     {
184
         NSDictionary *headers = [httpResponse allHeaderFields];
192
         NSDictionary *headers = [httpResponse allHeaderFields];
185
         NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
193
         NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
186
-        if(self.isServerPush == NO)
187
-        {
188
-            self.isServerPush = [[respCType lowercaseString] RNFBContainsString:@"multipart/x-mixed-replace;"];
189
-        }
190
-        if(self.isServerPush)
191
-        {
192
-            if(partBuffer != nil)
193
-            {
194
+        
195
+        if (self.isServerPush) {
196
+            if (partBuffer) {
194
                 [self.bridge.eventDispatcher
197
                 [self.bridge.eventDispatcher
195
                  sendDeviceEventWithName:EVENT_SERVER_PUSH
198
                  sendDeviceEventWithName:EVENT_SERVER_PUSH
196
                  body:@{
199
                  body:@{
199
                         }
202
                         }
200
                  ];
203
                  ];
201
             }
204
             }
205
+            
202
             partBuffer = [[NSMutableData alloc] init];
206
             partBuffer = [[NSMutableData alloc] init];
203
             completionHandler(NSURLSessionResponseAllow);
207
             completionHandler(NSURLSessionResponseAllow);
208
+
204
             return;
209
             return;
210
+        } else {
211
+            self.isServerPush = [[respCType lowercaseString] RNFBContainsString:@"multipart/x-mixed-replace;"];
205
         }
212
         }
206
-        if(respCType != nil)
213
+        
214
+        if(respCType)
207
         {
215
         {
208
             NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
216
             NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
209
-            if([respCType RNFBContainsString:@"text/"])
210
-            {
217
+            
218
+            if ([respCType RNFBContainsString:@"text/"]) {
211
                 respType = @"text";
219
                 respType = @"text";
212
-            }
213
-            else if([respCType RNFBContainsString:@"application/json"])
214
-            {
220
+            } else if ([respCType RNFBContainsString:@"application/json"]) {
215
                 respType = @"json";
221
                 respType = @"json";
216
-            }
217
-            // If extra blob content type is not empty, check if response type matches
218
-            else if( extraBlobCTypes !=  nil) {
219
-                for(NSString * substr in extraBlobCTypes)
220
-                {
221
-                    if([respCType RNFBContainsString:[substr lowercaseString]])
222
-                    {
222
+            } else if(extraBlobCTypes) { // If extra blob content type is not empty, check if response type matches
223
+                for (NSString * substr in extraBlobCTypes) {
224
+                    if ([respCType RNFBContainsString:[substr lowercaseString]]) {
223
                         respType = @"blob";
225
                         respType = @"blob";
224
                         respFile = YES;
226
                         respFile = YES;
225
                         destPath = [RNFetchBlobFS getTempPath:taskId withExtension:nil];
227
                         destPath = [RNFetchBlobFS getTempPath:taskId withExtension:nil];
226
                         break;
228
                         break;
227
                     }
229
                     }
228
                 }
230
                 }
229
-            }
230
-            else
231
-            {
231
+            } else {
232
                 respType = @"blob";
232
                 respType = @"blob";
233
+                
233
                 // for XMLHttpRequest, switch response data handling strategy automatically
234
                 // for XMLHttpRequest, switch response data handling strategy automatically
234
-                if([options valueForKey:@"auto"]) {
235
+                if ([options valueForKey:@"auto"]) {
235
                     respFile = YES;
236
                     respFile = YES;
236
                     destPath = [RNFetchBlobFS getTempPath:taskId withExtension:@""];
237
                     destPath = [RNFetchBlobFS getTempPath:taskId withExtension:@""];
237
                 }
238
                 }
242
         
243
         
243
 #pragma mark - handling cookies
244
 #pragma mark - handling cookies
244
         // # 153 get cookies
245
         // # 153 get cookies
245
-        if(response.URL != nil)
246
-        {
246
+        if (response.URL) {
247
             NSHTTPCookieStorage * cookieStore = [NSHTTPCookieStorage sharedHTTPCookieStorage];
247
             NSHTTPCookieStorage * cookieStore = [NSHTTPCookieStorage sharedHTTPCookieStorage];
248
             NSArray<NSHTTPCookie *> * cookies = [NSHTTPCookie cookiesWithResponseHeaderFields: headers forURL:response.URL];
248
             NSArray<NSHTTPCookie *> * cookies = [NSHTTPCookie cookiesWithResponseHeaderFields: headers forURL:response.URL];
249
-            if(cookies != nil && [cookies count] > 0) {
249
+            if (cookies.count) {
250
                 [cookieStore setCookies:cookies forURL:response.URL mainDocumentURL:nil];
250
                 [cookieStore setCookies:cookies forURL:response.URL mainDocumentURL:nil];
251
             }
251
             }
252
         }
252
         }
263
                 @"status": [NSNumber numberWithInteger:statusCode]
263
                 @"status": [NSNumber numberWithInteger:statusCode]
264
                 }
264
                 }
265
          ];
265
          ];
266
-    }
267
-    else
266
+    } else {
268
         NSLog(@"oops");
267
         NSLog(@"oops");
268
+    }
269
     
269
     
270
-    if(respFile == YES)
270
+    if (respFile)
271
     {
271
     {
272
         @try{
272
         @try{
273
             NSFileManager * fm = [NSFileManager defaultManager];
273
             NSFileManager * fm = [NSFileManager defaultManager];
274
             NSString * folder = [destPath stringByDeletingLastPathComponent];
274
             NSString * folder = [destPath stringByDeletingLastPathComponent];
275
-            if(![fm fileExistsAtPath:folder])
276
-            {
275
+            
276
+            if (![fm fileExistsAtPath:folder]) {
277
                 [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
277
                 [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
278
             }
278
             }
279
+            
280
+            // if not set overwrite in options, defaults to TRUE
279
             BOOL overwrite = [options valueForKey:@"overwrite"] == nil ? YES : [[options valueForKey:@"overwrite"] boolValue];
281
             BOOL overwrite = [options valueForKey:@"overwrite"] == nil ? YES : [[options valueForKey:@"overwrite"] boolValue];
280
             BOOL appendToExistingFile = [destPath RNFBContainsString:@"?append=true"];
282
             BOOL appendToExistingFile = [destPath RNFBContainsString:@"?append=true"];
281
             
283
             
283
             
285
             
284
             // For solving #141 append response data if the file already exists
286
             // For solving #141 append response data if the file already exists
285
             // base on PR#139 @kejinliang
287
             // base on PR#139 @kejinliang
286
-            if(appendToExistingFile)
287
-            {
288
+            if (appendToExistingFile) {
288
                 destPath = [destPath stringByReplacingOccurrencesOfString:@"?append=true" withString:@""];
289
                 destPath = [destPath stringByReplacingOccurrencesOfString:@"?append=true" withString:@""];
289
             }
290
             }
290
-            if (![fm fileExistsAtPath:destPath])
291
-            {
291
+            
292
+            if (![fm fileExistsAtPath:destPath]) {
292
                 [fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
293
                 [fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
293
             }
294
             }
295
+            
294
             writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:appendToExistingFile];
296
             writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:appendToExistingFile];
295
             [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
297
             [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
296
             [writeStream open];
298
             [writeStream open];
309
 - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
311
 - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
310
 {
312
 {
311
     // For #143 handling multipart/x-mixed-replace response
313
     // For #143 handling multipart/x-mixed-replace response
312
-    if(self.isServerPush)
314
+    if (self.isServerPush)
313
     {
315
     {
314
         [partBuffer appendData:data];
316
         [partBuffer appendData:data];
317
+        
315
         return ;
318
         return ;
316
     }
319
     }
317
     
320
     
319
     receivedBytes += [received longValue];
322
     receivedBytes += [received longValue];
320
     NSString * chunkString = @"";
323
     NSString * chunkString = @"";
321
     
324
     
322
-    if(isIncrement == YES)
323
-    {
325
+    if (isIncrement) {
324
         chunkString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
326
         chunkString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
325
     }
327
     }
326
     
328
     
327
-    if(respFile == NO)
328
-    {
329
-        [respData appendData:data];
330
-    }
331
-    else
332
-    {
329
+    if (respFile) {
333
         [writeStream write:[data bytes] maxLength:[data length]];
330
         [writeStream write:[data bytes] maxLength:[data length]];
331
+    } else {
332
+        [respData appendData:data];
334
     }
333
     }
335
     
334
     
336
-    if(expectedBytes == 0)
335
+    if (expectedBytes == 0) {
337
         return;
336
         return;
337
+    }
338
     
338
     
339
     NSNumber * now =[NSNumber numberWithFloat:((float)receivedBytes/(float)expectedBytes)];
339
     NSNumber * now =[NSNumber numberWithFloat:((float)receivedBytes/(float)expectedBytes)];
340
     
340
     
341
-    if([self.progressConfig shouldReport:now])
342
-    {
341
+    if ([self.progressConfig shouldReport:now]) {
343
         [self.bridge.eventDispatcher
342
         [self.bridge.eventDispatcher
344
          sendDeviceEventWithName:EVENT_PROGRESS
343
          sendDeviceEventWithName:EVENT_PROGRESS
345
          body:@{
344
          body:@{
354
 
353
 
355
 - (void) URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
354
 - (void) URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
356
 {
355
 {
357
-    if([session isEqual:session])
356
+    if ([session isEqual:session]) {
358
         session = nil;
357
         session = nil;
358
+    }
359
 }
359
 }
360
 
360
 
361
 
361
 
369
     
369
     
370
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
370
     [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
371
     
371
     
372
-    if(error != nil)
373
-    {
372
+    if (error) {
374
         errMsg = [error localizedDescription];
373
         errMsg = [error localizedDescription];
375
     }
374
     }
376
     
375
     
377
-    if(respFile == YES)
378
-    {
376
+    if (respFile) {
379
         [writeStream close];
377
         [writeStream close];
380
         rnfbRespType = RESP_TYPE_PATH;
378
         rnfbRespType = RESP_TYPE_PATH;
381
         respStr = destPath;
379
         respStr = destPath;
382
-    }
383
-    // base64 response
384
-    else {
380
+    } else { // base64 response
385
         // #73 fix unicode data encoding issue :
381
         // #73 fix unicode data encoding issue :
386
         // when response type is BASE64, we should first try to encode the response data to UTF8 format
382
         // when response type is BASE64, we should first try to encode the response data to UTF8 format
387
         // if it turns out not to be `nil` that means the response data contains valid UTF8 string,
383
         // if it turns out not to be `nil` that means the response data contains valid UTF8 string,
388
         // in order to properly encode the UTF8 string, use URL encoding before BASE64 encoding.
384
         // in order to properly encode the UTF8 string, use URL encoding before BASE64 encoding.
389
         NSString * utf8 = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
385
         NSString * utf8 = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
390
         
386
         
391
-        if(responseFormat == BASE64)
392
-        {
387
+        if (responseFormat == BASE64) {
393
             rnfbRespType = RESP_TYPE_BASE64;
388
             rnfbRespType = RESP_TYPE_BASE64;
394
             respStr = [respData base64EncodedStringWithOptions:0];
389
             respStr = [respData base64EncodedStringWithOptions:0];
395
-        }
396
-        else if (responseFormat == UTF8)
397
-        {
390
+        } else if (responseFormat == UTF8) {
398
             rnfbRespType = RESP_TYPE_UTF8;
391
             rnfbRespType = RESP_TYPE_UTF8;
399
             respStr = utf8;
392
             respStr = utf8;
400
-        }
401
-        else
402
-        {
403
-            if(utf8 != nil)
404
-            {
393
+        } else {
394
+            if (utf8) {
405
                 rnfbRespType = RESP_TYPE_UTF8;
395
                 rnfbRespType = RESP_TYPE_UTF8;
406
                 respStr = utf8;
396
                 respStr = utf8;
407
-            }
408
-            else
409
-            {
397
+            } else {
410
                 rnfbRespType = RESP_TYPE_BASE64;
398
                 rnfbRespType = RESP_TYPE_BASE64;
411
                 respStr = [respData base64EncodedStringWithOptions:0];
399
                 respStr = [respData base64EncodedStringWithOptions:0];
412
             }
400
             }
429
 // upload progress handler
417
 // upload progress handler
430
 - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
418
 - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
431
 {
419
 {
432
-    if(totalBytesExpectedToWrite == 0)
420
+    if (totalBytesExpectedToWrite == 0) {
433
         return;
421
         return;
422
+    }
434
     
423
     
435
     NSNumber * now = [NSNumber numberWithFloat:((float)totalBytesWritten/(float)totalBytesExpectedToWrite)];
424
     NSNumber * now = [NSNumber numberWithFloat:((float)totalBytesWritten/(float)totalBytesExpectedToWrite)];
436
 
425
 
437
-    if([self.uploadProgressConfig shouldReport:now]) {
426
+    if ([self.uploadProgressConfig shouldReport:now]) {
438
         [self.bridge.eventDispatcher
427
         [self.bridge.eventDispatcher
439
          sendDeviceEventWithName:EVENT_PROGRESS_UPLOAD
428
          sendDeviceEventWithName:EVENT_PROGRESS_UPLOAD
440
          body:@{
429
          body:@{
449
 
438
 
450
 - (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable credantial))completionHandler
439
 - (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable credantial))completionHandler
451
 {
440
 {
452
-    BOOL trusty = [[options valueForKey:CONFIG_TRUSTY] boolValue];
453
-    if(!trusty)
454
-    {
455
-        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
456
-    }
457
-    else
458
-    {
441
+    if ([[options valueForKey:CONFIG_TRUSTY] boolValue]) {
459
         completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
442
         completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
443
+    } else {
444
+        completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
460
     }
445
     }
461
 }
446
 }
462
 
447
 
469
 - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
454
 - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
470
 {
455
 {
471
     
456
     
472
-    if(followRedirect)
473
-    {
474
-        if(request.URL != nil)
457
+    if (followRedirect) {
458
+        if (request.URL) {
475
             [redirects addObject:[request.URL absoluteString]];
459
             [redirects addObject:[request.URL absoluteString]];
460
+        }
461
+        
476
         completionHandler(request);
462
         completionHandler(request);
477
-    }
478
-    else
479
-    {
463
+    } else {
480
         completionHandler(nil);
464
         completionHandler(nil);
481
     }
465
     }
482
 }
466
 }