瀏覽代碼

Some code guidelines for network classes

Artur Chrusciel 6 年之前
父節點
當前提交
57102f4d1e
共有 2 個檔案被更改,包括 97 行新增113 行删除
  1. 5
    5
      ios/RNFetchBlobNetwork.m
  2. 92
    108
      ios/RNFetchBlobRequest.m

+ 5
- 5
ios/RNFetchBlobNetwork.m 查看文件

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

+ 92
- 108
ios/RNFetchBlobRequest.m 查看文件

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