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

RNFetchBlobNetwork.m 21KB

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