Açıklama Yok

RNFetchBlobNetwork.m 20KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640
  1. //
  2. // RNFetchBlobNetwork.m
  3. // RNFetchBlob
  4. //
  5. // Created by wkh237 on 2016/6/6.
  6. // Copyright © 2016 wkh237. All rights reserved.
  7. //
  8. #import <Foundation/Foundation.h>
  9. #import "RNFetchBlob.h"
  10. #import "RNFetchBlobFS.h"
  11. #import "RNFetchBlobNetwork.h"
  12. #import "RNFetchBlobConst.h"
  13. #import "RNFetchBlobReqBuilder.h"
  14. #import "IOS7Polyfill.h"
  15. #import <CommonCrypto/CommonDigest.h>
  16. #import "RNFetchBlobProgress.h"
  17. #if __has_include(<React/RCTAssert.h>)
  18. #import <React/RCTRootView.h>
  19. #import <React/RCTLog.h>
  20. #import <React/RCTEventDispatcher.h>
  21. #import <React/RCTBridge.h>
  22. #else
  23. #import "RCTRootView.h"
  24. #import "RCTLog.h"
  25. #import "RCTEventDispatcher.h"
  26. #import "RCTBridge.h"
  27. #endif
  28. ////////////////////////////////////////
  29. //
  30. // HTTP request handler
  31. //
  32. ////////////////////////////////////////
  33. NSMapTable * taskTable;
  34. NSMapTable * expirationTable;
  35. NSMutableDictionary * progressTable;
  36. NSMutableDictionary * uploadProgressTable;
  37. __attribute__((constructor))
  38. static void initialize_tables() {
  39. if(expirationTable == nil)
  40. {
  41. expirationTable = [[NSMapTable alloc] init];
  42. }
  43. if(taskTable == nil)
  44. {
  45. taskTable = [[NSMapTable alloc] init];
  46. }
  47. if(progressTable == nil)
  48. {
  49. progressTable = [[NSMutableDictionary alloc] init];
  50. }
  51. if(uploadProgressTable == nil)
  52. {
  53. uploadProgressTable = [[NSMutableDictionary alloc] init];
  54. }
  55. }
  56. typedef NS_ENUM(NSUInteger, ResponseFormat) {
  57. UTF8,
  58. BASE64,
  59. AUTO
  60. };
  61. @interface RNFetchBlobNetwork ()
  62. {
  63. BOOL * respFile;
  64. BOOL isNewPart;
  65. BOOL * isIncrement;
  66. NSMutableData * partBuffer;
  67. NSString * destPath;
  68. NSOutputStream * writeStream;
  69. long bodyLength;
  70. NSMutableDictionary * respInfo;
  71. NSInteger respStatus;
  72. NSMutableArray * redirects;
  73. ResponseFormat responseFormat;
  74. BOOL * followRedirect;
  75. BOOL backgroundTask;
  76. }
  77. @end
  78. @implementation RNFetchBlobNetwork
  79. NSOperationQueue *taskQueue;
  80. @synthesize taskId;
  81. @synthesize expectedBytes;
  82. @synthesize receivedBytes;
  83. @synthesize respData;
  84. @synthesize callback;
  85. @synthesize bridge;
  86. @synthesize options;
  87. @synthesize fileTaskCompletionHandler;
  88. @synthesize dataTaskCompletionHandler;
  89. @synthesize error;
  90. // constructor
  91. - (id)init {
  92. self = [super init];
  93. if(taskQueue == nil) {
  94. @synchronized ([RNFetchBlobNetwork class]) {
  95. if (taskQueue == nil) {
  96. taskQueue = [[NSOperationQueue alloc] init];
  97. taskQueue.maxConcurrentOperationCount = 10;
  98. }
  99. }
  100. }
  101. return self;
  102. }
  103. + (void) enableProgressReport:(NSString *) taskId config:(RNFetchBlobProgress *)config
  104. {
  105. if(progressTable == nil)
  106. {
  107. progressTable = [[NSMutableDictionary alloc] init];
  108. }
  109. [progressTable setValue:config forKey:taskId];
  110. }
  111. + (void) enableUploadProgress:(NSString *) taskId config:(RNFetchBlobProgress *)config
  112. {
  113. if(uploadProgressTable == nil)
  114. {
  115. uploadProgressTable = [[NSMutableDictionary alloc] init];
  116. }
  117. [uploadProgressTable setValue:config forKey:taskId];
  118. }
  119. // removing case from headers
  120. + (NSMutableDictionary *) normalizeHeaders:(NSDictionary *)headers
  121. {
  122. NSMutableDictionary * mheaders = [[NSMutableDictionary alloc]init];
  123. for(NSString * key in headers) {
  124. [mheaders setValue:[headers valueForKey:key] forKey:[key lowercaseString]];
  125. }
  126. return mheaders;
  127. }
  128. - (NSString *)md5:(NSString *)input {
  129. const char* str = [input UTF8String];
  130. unsigned char result[CC_MD5_DIGEST_LENGTH];
  131. CC_MD5(str, (CC_LONG)strlen(str), result);
  132. NSMutableString *ret = [NSMutableString stringWithCapacity:CC_MD5_DIGEST_LENGTH*2];
  133. for(int i = 0; i<CC_MD5_DIGEST_LENGTH; i++) {
  134. [ret appendFormat:@"%02x",result[i]];
  135. }
  136. return ret;
  137. }
  138. // send HTTP request
  139. - (void) sendRequest:(__weak NSDictionary * _Nullable )options
  140. contentLength:(long) contentLength
  141. bridge:(RCTBridge * _Nullable)bridgeRef
  142. taskId:(NSString * _Nullable)taskId
  143. withRequest:(__weak NSURLRequest * _Nullable)req
  144. callback:(_Nullable RCTResponseSenderBlock) callback
  145. {
  146. self.taskId = taskId;
  147. self.respData = [[NSMutableData alloc] initWithLength:0];
  148. self.callback = callback;
  149. self.bridge = bridgeRef;
  150. self.expectedBytes = 0;
  151. self.receivedBytes = 0;
  152. self.options = options;
  153. backgroundTask = [options valueForKey:@"IOSBackgroundTask"] == nil ? NO : [[options valueForKey:@"IOSBackgroundTask"] boolValue];
  154. followRedirect = [options valueForKey:@"followRedirect"] == nil ? YES : [[options valueForKey:@"followRedirect"] boolValue];
  155. isIncrement = [options valueForKey:@"increment"] == nil ? NO : [[options valueForKey:@"increment"] boolValue];
  156. redirects = [[NSMutableArray alloc] init];
  157. if(req.URL != nil)
  158. [redirects addObject:req.URL.absoluteString];
  159. // set response format
  160. NSString * rnfbResp = [req.allHTTPHeaderFields valueForKey:@"RNFB-Response"];
  161. if([[rnfbResp lowercaseString] isEqualToString:@"base64"])
  162. responseFormat = BASE64;
  163. else if([[rnfbResp lowercaseString] isEqualToString:@"utf8"])
  164. responseFormat = UTF8;
  165. else
  166. responseFormat = AUTO;
  167. NSString * path = [self.options valueForKey:CONFIG_FILE_PATH];
  168. NSString * ext = [self.options valueForKey:CONFIG_FILE_EXT];
  169. NSString * key = [self.options valueForKey:CONFIG_KEY];
  170. __block NSURLSession * session;
  171. bodyLength = contentLength;
  172. // the session trust any SSL certification
  173. NSURLSessionConfiguration *defaultConfigObject;
  174. defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
  175. if(backgroundTask)
  176. {
  177. defaultConfigObject = [NSURLSessionConfiguration backgroundSessionConfigurationWithIdentifier:taskId];
  178. }
  179. // set request timeout
  180. float timeout = [options valueForKey:@"timeout"] == nil ? -1 : [[options valueForKey:@"timeout"] floatValue];
  181. if(timeout > 0)
  182. {
  183. defaultConfigObject.timeoutIntervalForRequest = timeout/1000;
  184. }
  185. defaultConfigObject.HTTPMaximumConnectionsPerHost = 10;
  186. session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:taskQueue];
  187. if(path != nil || [self.options valueForKey:CONFIG_USE_TEMP]!= nil)
  188. {
  189. respFile = YES;
  190. NSString* cacheKey = taskId;
  191. if (key != nil) {
  192. cacheKey = [self md5:key];
  193. if (cacheKey == nil) {
  194. cacheKey = taskId;
  195. }
  196. destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
  197. if ([[NSFileManager defaultManager] fileExistsAtPath:destPath]) {
  198. callback(@[[NSNull null], RESP_TYPE_PATH, destPath]);
  199. return;
  200. }
  201. }
  202. if(path != nil)
  203. destPath = path;
  204. else
  205. destPath = [RNFetchBlobFS getTempPath:cacheKey withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
  206. }
  207. else
  208. {
  209. respData = [[NSMutableData alloc] init];
  210. respFile = NO;
  211. }
  212. __block NSURLSessionDataTask * task = [session dataTaskWithRequest:req];
  213. [taskTable setObject:@{ @"session" : task, @"isCancelled" : @NO } forKey:taskId];
  214. [task resume];
  215. // network status indicator
  216. if ([[options objectForKey:CONFIG_INDICATOR] boolValue] == YES) {
  217. dispatch_async(dispatch_get_main_queue(), ^{
  218. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  219. });
  220. }
  221. __block UIApplication * app = [UIApplication sharedApplication];
  222. }
  223. // #115 Invoke fetch.expire event on those expired requests so that the expired event can be handled
  224. + (void) emitExpiredTasks
  225. {
  226. NSEnumerator * emu = [expirationTable keyEnumerator];
  227. NSString * key;
  228. while((key = [emu nextObject]))
  229. {
  230. RCTBridge * bridge = [RNFetchBlob getRCTBridge];
  231. NSData * args = @{ @"taskId": key };
  232. [bridge.eventDispatcher sendDeviceEventWithName:EVENT_EXPIRE body:args];
  233. }
  234. // clear expired task entries
  235. [expirationTable removeAllObjects];
  236. expirationTable = [[NSMapTable alloc] init];
  237. }
  238. ////////////////////////////////////////
  239. //
  240. // NSURLSession delegates
  241. //
  242. ////////////////////////////////////////
  243. #pragma mark NSURLSession delegate methods
  244. #pragma mark - Received Response
  245. // set expected content length on response received
  246. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
  247. {
  248. expectedBytes = [response expectedContentLength];
  249. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  250. NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
  251. NSString * respType = @"";
  252. respStatus = statusCode;
  253. if ([response respondsToSelector:@selector(allHeaderFields)])
  254. {
  255. NSDictionary *headers = [httpResponse allHeaderFields];
  256. NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
  257. if(self.isServerPush == NO)
  258. {
  259. self.isServerPush = [[respCType lowercaseString] RNFBContainsString:@"multipart/x-mixed-replace;"];
  260. }
  261. if(self.isServerPush)
  262. {
  263. if(partBuffer != nil)
  264. {
  265. [self.bridge.eventDispatcher
  266. sendDeviceEventWithName:EVENT_SERVER_PUSH
  267. body:@{
  268. @"taskId": taskId,
  269. @"chunk": [partBuffer base64EncodedStringWithOptions:0],
  270. }
  271. ];
  272. }
  273. partBuffer = [[NSMutableData alloc] init];
  274. completionHandler(NSURLSessionResponseAllow);
  275. return;
  276. }
  277. if(respCType != nil)
  278. {
  279. NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
  280. if([respCType RNFBContainsString:@"text/"])
  281. {
  282. respType = @"text";
  283. }
  284. else if([respCType RNFBContainsString:@"application/json"])
  285. {
  286. respType = @"json";
  287. }
  288. // If extra blob content type is not empty, check if response type matches
  289. else if( extraBlobCTypes != nil) {
  290. for(NSString * substr in extraBlobCTypes)
  291. {
  292. if([respCType RNFBContainsString:[substr lowercaseString]])
  293. {
  294. respType = @"blob";
  295. respFile = YES;
  296. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:nil];
  297. break;
  298. }
  299. }
  300. }
  301. else
  302. {
  303. respType = @"blob";
  304. // for XMLHttpRequest, switch response data handling strategy automatically
  305. if([options valueForKey:@"auto"] == YES) {
  306. respFile = YES;
  307. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:@""];
  308. }
  309. }
  310. }
  311. else
  312. respType = @"text";
  313. respInfo = @{
  314. @"taskId": taskId,
  315. @"state": @"2",
  316. @"headers": headers,
  317. @"redirects": redirects,
  318. @"respType" : respType,
  319. @"timeout" : @NO,
  320. @"status": [NSNumber numberWithInteger:statusCode]
  321. };
  322. #pragma mark - handling cookies
  323. // # 153 get cookies
  324. if(response.URL != nil)
  325. {
  326. NSHTTPCookieStorage * cookieStore = [NSHTTPCookieStorage sharedHTTPCookieStorage];
  327. NSArray<NSHTTPCookie *> * cookies = [NSHTTPCookie cookiesWithResponseHeaderFields: headers forURL:response.URL];
  328. if(cookies != nil && [cookies count] > 0) {
  329. [cookieStore setCookies:cookies forURL:response.URL mainDocumentURL:nil];
  330. }
  331. }
  332. [self.bridge.eventDispatcher
  333. sendDeviceEventWithName: EVENT_STATE_CHANGE
  334. body:respInfo
  335. ];
  336. headers = nil;
  337. respInfo = nil;
  338. }
  339. else
  340. NSLog(@"oops");
  341. if(respFile == YES)
  342. {
  343. @try{
  344. NSFileManager * fm = [NSFileManager defaultManager];
  345. NSString * folder = [destPath stringByDeletingLastPathComponent];
  346. if(![fm fileExistsAtPath:folder])
  347. {
  348. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
  349. }
  350. BOOL overwrite = [options valueForKey:@"overwrite"] == nil ? YES : [[options valueForKey:@"overwrite"] boolValue];
  351. BOOL appendToExistingFile = [destPath RNFBContainsString:@"?append=true"];
  352. appendToExistingFile = !overwrite;
  353. // For solving #141 append response data if the file already exists
  354. // base on PR#139 @kejinliang
  355. if(appendToExistingFile)
  356. {
  357. destPath = [destPath stringByReplacingOccurrencesOfString:@"?append=true" withString:@""];
  358. }
  359. if (![fm fileExistsAtPath:destPath])
  360. {
  361. [fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
  362. }
  363. writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:appendToExistingFile];
  364. [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  365. [writeStream open];
  366. }
  367. @catch(NSException * ex)
  368. {
  369. NSLog(@"write file error");
  370. }
  371. }
  372. completionHandler(NSURLSessionResponseAllow);
  373. }
  374. // download progress handler
  375. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  376. {
  377. // For #143 handling multipart/x-mixed-replace response
  378. if(self.isServerPush)
  379. {
  380. [partBuffer appendData:data];
  381. return ;
  382. }
  383. NSNumber * received = [NSNumber numberWithLong:[data length]];
  384. receivedBytes += [received longValue];
  385. NSString * chunkString = @"";
  386. if(isIncrement == YES)
  387. {
  388. chunkString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  389. }
  390. if(respFile == NO)
  391. {
  392. [respData appendData:data];
  393. }
  394. else
  395. {
  396. [writeStream write:[data bytes] maxLength:[data length]];
  397. }
  398. RNFetchBlobProgress * pconfig = [progressTable valueForKey:taskId];
  399. if(expectedBytes == 0)
  400. return;
  401. NSNumber * now =[NSNumber numberWithFloat:((float)receivedBytes/(float)expectedBytes)];
  402. if(pconfig != nil && [pconfig shouldReport:now])
  403. {
  404. [self.bridge.eventDispatcher
  405. sendDeviceEventWithName:EVENT_PROGRESS
  406. body:@{
  407. @"taskId": taskId,
  408. @"written": [NSString stringWithFormat:@"%d", receivedBytes],
  409. @"total": [NSString stringWithFormat:@"%d", expectedBytes],
  410. @"chunk": chunkString
  411. }
  412. ];
  413. }
  414. received = nil;
  415. }
  416. - (void) URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
  417. {
  418. if([session isEqual:session])
  419. session = nil;
  420. }
  421. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  422. {
  423. self.error = error;
  424. NSString * errMsg = [NSNull null];
  425. NSString * respStr = [NSNull null];
  426. NSString * rnfbRespType = @"";
  427. dispatch_async(dispatch_get_main_queue(), ^{
  428. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  429. });
  430. if(respInfo == nil)
  431. {
  432. respInfo = [NSNull null];
  433. }
  434. if(error != nil)
  435. {
  436. errMsg = [error localizedDescription];
  437. }
  438. NSDictionary * taskSession = [taskTable objectForKey:taskId];
  439. BOOL isCancelled = [[taskSession valueForKey:@"isCancelled"] boolValue];
  440. if(isCancelled) {
  441. errMsg = @"task cancelled";
  442. }
  443. if(respFile == YES)
  444. {
  445. [writeStream close];
  446. rnfbRespType = RESP_TYPE_PATH;
  447. respStr = destPath;
  448. }
  449. // base64 response
  450. else {
  451. // #73 fix unicode data encoding issue :
  452. // when response type is BASE64, we should first try to encode the response data to UTF8 format
  453. // if it turns out not to be `nil` that means the response data contains valid UTF8 string,
  454. // in order to properly encode the UTF8 string, use URL encoding before BASE64 encoding.
  455. NSString * utf8 = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
  456. if(responseFormat == BASE64)
  457. {
  458. rnfbRespType = RESP_TYPE_BASE64;
  459. respStr = [respData base64EncodedStringWithOptions:0];
  460. }
  461. else if (responseFormat == UTF8)
  462. {
  463. rnfbRespType = RESP_TYPE_UTF8;
  464. respStr = utf8;
  465. }
  466. else
  467. {
  468. if(utf8 != nil)
  469. {
  470. rnfbRespType = RESP_TYPE_UTF8;
  471. respStr = utf8;
  472. }
  473. else
  474. {
  475. rnfbRespType = RESP_TYPE_BASE64;
  476. respStr = [respData base64EncodedStringWithOptions:0];
  477. }
  478. }
  479. }
  480. callback(@[ errMsg, rnfbRespType, respStr]);
  481. @synchronized(taskTable, uploadProgressTable, progressTable)
  482. {
  483. if([taskTable objectForKey:taskId] == nil)
  484. NSLog(@"object released by ARC.");
  485. else
  486. [taskTable removeObjectForKey:taskId];
  487. [uploadProgressTable removeObjectForKey:taskId];
  488. [progressTable removeObjectForKey:taskId];
  489. }
  490. respData = nil;
  491. receivedBytes = 0;
  492. [session finishTasksAndInvalidate];
  493. }
  494. // upload progress handler
  495. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
  496. {
  497. RNFetchBlobProgress * pconfig = [uploadProgressTable valueForKey:taskId];
  498. if(totalBytesExpectedToWrite == 0)
  499. return;
  500. NSNumber * now = [NSNumber numberWithFloat:((float)totalBytesWritten/(float)totalBytesExpectedToWrite)];
  501. if(pconfig != nil && [pconfig shouldReport:now]) {
  502. [self.bridge.eventDispatcher
  503. sendDeviceEventWithName:EVENT_PROGRESS_UPLOAD
  504. body:@{
  505. @"taskId": taskId,
  506. @"written": [NSString stringWithFormat:@"%d", totalBytesWritten],
  507. @"total": [NSString stringWithFormat:@"%d", totalBytesExpectedToWrite]
  508. }
  509. ];
  510. }
  511. }
  512. + (void) cancelRequest:(NSString *)taskId
  513. {
  514. NSDictionary * task = [taskTable objectForKey:taskId];
  515. if(task != nil) {
  516. NSURLSessionDataTask * session = [task objectForKey:@"session"];
  517. if(session.state == NSURLSessionTaskStateRunning) {
  518. [task setValue:@NO forKey:@"isCancelled"];
  519. [session cancel];
  520. }
  521. }
  522. }
  523. - (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable credantial))completionHandler
  524. {
  525. BOOL trusty = [options valueForKey:CONFIG_TRUSTY];
  526. if(!trusty)
  527. {
  528. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  529. }
  530. else
  531. {
  532. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  533. }
  534. }
  535. - (void) URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
  536. {
  537. NSLog(@"sess done in background");
  538. }
  539. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
  540. {
  541. if(followRedirect)
  542. {
  543. if(request.URL != nil)
  544. [redirects addObject:[request.URL absoluteString]];
  545. completionHandler(request);
  546. }
  547. else
  548. {
  549. completionHandler(nil);
  550. }
  551. }
  552. @end