Keine Beschreibung

RNFetchBlobNetwork.m 20KB

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