Açıklama Yok

RNFetchBlobNetwork.m 21KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669
  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. [app endBackgroundTask:tid];
  261. }];
  262. }
  263. // #115 Invoke fetch.expire event on those expired requests so that the expired event can be handled
  264. + (void) emitExpiredTasks
  265. {
  266. NSEnumerator * emu = [expirationTable keyEnumerator];
  267. NSString * key;
  268. while((key = [emu nextObject]))
  269. {
  270. RCTBridge * bridge = [RNFetchBlob getRCTBridge];
  271. NSData * args = @{ @"taskId": key };
  272. [bridge.eventDispatcher sendDeviceEventWithName:EVENT_EXPIRE body:args];
  273. }
  274. // clear expired task entries
  275. [expirationTable removeAllObjects];
  276. expirationTable = [[NSMapTable alloc] init];
  277. }
  278. ////////////////////////////////////////
  279. //
  280. // NSURLSession delegates
  281. //
  282. ////////////////////////////////////////
  283. #pragma mark NSURLSession delegate methods
  284. #pragma mark - Received Response
  285. // set expected content length on response received
  286. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
  287. {
  288. expectedBytes = [response expectedContentLength];
  289. NSHTTPURLResponse *httpResponse = (NSHTTPURLResponse*)response;
  290. NSInteger statusCode = [(NSHTTPURLResponse *)response statusCode];
  291. NSString * respType = @"";
  292. respStatus = statusCode;
  293. if ([response respondsToSelector:@selector(allHeaderFields)])
  294. {
  295. NSDictionary *headers = [httpResponse allHeaderFields];
  296. NSString * respCType = [[RNFetchBlobReqBuilder getHeaderIgnoreCases:@"Content-Type" fromHeaders:headers] lowercaseString];
  297. if(self.isServerPush == NO)
  298. {
  299. self.isServerPush = [[respCType lowercaseString] RNFBContainsString:@"multipart/x-mixed-replace;"];
  300. }
  301. if(self.isServerPush)
  302. {
  303. if(partBuffer != nil)
  304. {
  305. [self.bridge.eventDispatcher
  306. sendDeviceEventWithName:EVENT_SERVER_PUSH
  307. body:@{
  308. @"taskId": taskId,
  309. @"chunk": [partBuffer base64EncodedStringWithOptions:0],
  310. }
  311. ];
  312. }
  313. partBuffer = [[NSMutableData alloc] init];
  314. completionHandler(NSURLSessionResponseAllow);
  315. return;
  316. }
  317. if(respCType != nil)
  318. {
  319. NSArray * extraBlobCTypes = [options objectForKey:CONFIG_EXTRA_BLOB_CTYPE];
  320. if([respCType RNFBContainsString:@"text/"])
  321. {
  322. respType = @"text";
  323. }
  324. else if([respCType RNFBContainsString:@"application/json"])
  325. {
  326. respType = @"json";
  327. }
  328. // If extra blob content type is not empty, check if response type matches
  329. else if( extraBlobCTypes != nil) {
  330. for(NSString * substr in extraBlobCTypes)
  331. {
  332. if([respCType RNFBContainsString:[substr lowercaseString]])
  333. {
  334. respType = @"blob";
  335. respFile = YES;
  336. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:nil];
  337. break;
  338. }
  339. }
  340. }
  341. else
  342. {
  343. respType = @"blob";
  344. // for XMLHttpRequest, switch response data handling strategy automatically
  345. if([options valueForKey:@"auto"] == YES) {
  346. respFile = YES;
  347. destPath = [RNFetchBlobFS getTempPath:taskId withExtension:@""];
  348. }
  349. }
  350. }
  351. else
  352. respType = @"text";
  353. respInfo = @{
  354. @"taskId": taskId,
  355. @"state": @"2",
  356. @"headers": headers,
  357. @"redirects": redirects,
  358. @"respType" : respType,
  359. @"timeout" : @NO,
  360. @"status": [NSNumber numberWithInteger:statusCode]
  361. };
  362. #pragma mark - handling cookies
  363. // # 153 get cookies
  364. if(response.URL != nil)
  365. {
  366. NSArray<NSHTTPCookie *> * cookies = [NSHTTPCookie cookiesWithResponseHeaderFields: headers forURL:response.URL];
  367. if(cookies != nil && [cookies count] > 0) {
  368. [cookiesTable setObject:cookies forKey:response.URL.host];
  369. }
  370. }
  371. [self.bridge.eventDispatcher
  372. sendDeviceEventWithName: EVENT_STATE_CHANGE
  373. body:respInfo
  374. ];
  375. headers = nil;
  376. respInfo = nil;
  377. }
  378. else
  379. NSLog(@"oops");
  380. if(respFile == YES)
  381. {
  382. @try{
  383. NSFileManager * fm = [NSFileManager defaultManager];
  384. NSString * folder = [destPath stringByDeletingLastPathComponent];
  385. if(![fm fileExistsAtPath:folder])
  386. {
  387. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:nil];
  388. }
  389. BOOL overwrite = [options valueForKey:@"overwrite"] == nil ? YES : [[options valueForKey:@"overwrite"] boolValue];
  390. BOOL appendToExistingFile = [destPath RNFBContainsString:@"?append=true"];
  391. appendToExistingFile = !overwrite;
  392. // For solving #141 append response data if the file already exists
  393. // base on PR#139 @kejinliang
  394. if(appendToExistingFile)
  395. {
  396. destPath = [destPath stringByReplacingOccurrencesOfString:@"?append=true" withString:@""];
  397. }
  398. if (![fm fileExistsAtPath:destPath])
  399. {
  400. [fm createFileAtPath:destPath contents:[[NSData alloc] init] attributes:nil];
  401. }
  402. writeStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:appendToExistingFile];
  403. [writeStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  404. [writeStream open];
  405. }
  406. @catch(NSException * ex)
  407. {
  408. NSLog(@"write file error");
  409. }
  410. }
  411. completionHandler(NSURLSessionResponseAllow);
  412. }
  413. // download progress handler
  414. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  415. {
  416. // For #143 handling multipart/x-mixed-replace response
  417. if(self.isServerPush)
  418. {
  419. [partBuffer appendData:data];
  420. return ;
  421. }
  422. NSNumber * received = [NSNumber numberWithLong:[data length]];
  423. receivedBytes += [received longValue];
  424. NSString * chunkString = @"";
  425. if(isIncrement == YES)
  426. {
  427. chunkString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
  428. }
  429. if(respFile == NO)
  430. {
  431. [respData appendData:data];
  432. }
  433. else
  434. {
  435. [writeStream write:[data bytes] maxLength:[data length]];
  436. }
  437. RNFetchBlobProgress * pconfig = [progressTable valueForKey:taskId];
  438. if(expectedBytes == 0)
  439. return;
  440. NSNumber * now =[NSNumber numberWithFloat:((float)receivedBytes/(float)expectedBytes)];
  441. if(pconfig != nil && [pconfig shouldReport:now])
  442. {
  443. [self.bridge.eventDispatcher
  444. sendDeviceEventWithName:EVENT_PROGRESS
  445. body:@{
  446. @"taskId": taskId,
  447. @"written": [NSString stringWithFormat:@"%d", receivedBytes],
  448. @"total": [NSString stringWithFormat:@"%d", expectedBytes],
  449. @"chunk": chunkString
  450. }
  451. ];
  452. }
  453. received = nil;
  454. }
  455. - (void) URLSession:(NSURLSession *)session didBecomeInvalidWithError:(nullable NSError *)error
  456. {
  457. if([session isEqual:session])
  458. session = nil;
  459. }
  460. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error
  461. {
  462. self.error = error;
  463. NSString * errMsg = [NSNull null];
  464. NSString * respStr = [NSNull null];
  465. NSString * rnfbRespType = @"";
  466. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  467. if(respInfo == nil)
  468. {
  469. respInfo = [NSNull null];
  470. }
  471. if(error != nil)
  472. {
  473. errMsg = [error localizedDescription];
  474. }
  475. if(respFile == YES)
  476. {
  477. [writeStream close];
  478. rnfbRespType = RESP_TYPE_PATH;
  479. respStr = destPath;
  480. }
  481. // base64 response
  482. else {
  483. // #73 fix unicode data encoding issue :
  484. // when response type is BASE64, we should first try to encode the response data to UTF8 format
  485. // if it turns out not to be `nil` that means the response data contains valid UTF8 string,
  486. // in order to properly encode the UTF8 string, use URL encoding before BASE64 encoding.
  487. NSString * utf8 = [[NSString alloc] initWithData:respData encoding:NSUTF8StringEncoding];
  488. if(responseFormat == BASE64)
  489. {
  490. rnfbRespType = RESP_TYPE_BASE64;
  491. respStr = [respData base64EncodedStringWithOptions:0];
  492. }
  493. else if (responseFormat == UTF8)
  494. {
  495. rnfbRespType = RESP_TYPE_UTF8;
  496. respStr = utf8;
  497. }
  498. else
  499. {
  500. if(utf8 != nil)
  501. {
  502. rnfbRespType = RESP_TYPE_UTF8;
  503. respStr = utf8;
  504. }
  505. else
  506. {
  507. rnfbRespType = RESP_TYPE_BASE64;
  508. respStr = [respData base64EncodedStringWithOptions:0];
  509. }
  510. }
  511. }
  512. callback(@[ errMsg, rnfbRespType, respStr]);
  513. @synchronized(taskTable, uploadProgressTable, progressTable)
  514. {
  515. if([taskTable objectForKey:taskId] == nil)
  516. NSLog(@"object released by ARC.");
  517. else
  518. [taskTable removeObjectForKey:taskId];
  519. [uploadProgressTable removeObjectForKey:taskId];
  520. [progressTable removeObjectForKey:taskId];
  521. }
  522. respData = nil;
  523. receivedBytes = 0;
  524. [session finishTasksAndInvalidate];
  525. }
  526. // upload progress handler
  527. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
  528. {
  529. RNFetchBlobProgress * pconfig = [uploadProgressTable valueForKey:taskId];
  530. if(totalBytesExpectedToWrite == 0)
  531. return;
  532. NSNumber * now = [NSNumber numberWithFloat:((float)totalBytesWritten/(float)totalBytesExpectedToWrite)];
  533. if(pconfig != nil && [pconfig shouldReport:now]) {
  534. [self.bridge.eventDispatcher
  535. sendDeviceEventWithName:EVENT_PROGRESS_UPLOAD
  536. body:@{
  537. @"taskId": taskId,
  538. @"written": [NSString stringWithFormat:@"%d", totalBytesWritten],
  539. @"total": [NSString stringWithFormat:@"%d", totalBytesExpectedToWrite]
  540. }
  541. ];
  542. }
  543. }
  544. + (void) cancelRequest:(NSString *)taskId
  545. {
  546. NSURLSessionDataTask * task = [taskTable objectForKey:taskId];
  547. if(task != nil && task.state == NSURLSessionTaskStateRunning)
  548. [task cancel];
  549. }
  550. - (void) URLSession:(NSURLSession *)session didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable credantial))completionHandler
  551. {
  552. BOOL trusty = [options valueForKey:CONFIG_TRUSTY];
  553. if(!trusty)
  554. {
  555. completionHandler(NSURLSessionAuthChallengePerformDefaultHandling, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  556. }
  557. else
  558. {
  559. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  560. }
  561. }
  562. - (void) URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
  563. {
  564. NSLog(@"sess done in background");
  565. }
  566. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task willPerformHTTPRedirection:(NSHTTPURLResponse *)response newRequest:(NSURLRequest *)request completionHandler:(void (^)(NSURLRequest * _Nullable))completionHandler
  567. {
  568. if(followRedirect)
  569. {
  570. if(request.URL != nil)
  571. [redirects addObject:[request.URL absoluteString]];
  572. completionHandler(request);
  573. }
  574. else
  575. {
  576. completionHandler(nil);
  577. }
  578. }
  579. @end