Няма описание

RNFetchBlobNetwork.m 20KB

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