Aucune description

RNFetchBlobNetwork.m 8.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  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 "RCTConvert.h"
  9. #import "RCTLog.h"
  10. #import <Foundation/Foundation.h>
  11. #import "RCTBridge.h"
  12. #import "RCTEventDispatcher.h"
  13. #import "RNFetchBlobFS.h"
  14. #import "RNFetchBlobNetwork.h"
  15. #import "RNFetchBlobConst.h"
  16. ////////////////////////////////////////
  17. //
  18. // HTTP request handler
  19. //
  20. ////////////////////////////////////////
  21. @implementation RNFetchBlobNetwork
  22. NSOperationQueue *taskQueue;
  23. @synthesize taskId;
  24. @synthesize expectedBytes;
  25. @synthesize receivedBytes;
  26. @synthesize respData;
  27. @synthesize callback;
  28. @synthesize bridge;
  29. @synthesize options;
  30. //@synthesize fileTaskCompletionHandler;
  31. //@synthesize dataTaskCompletionHandler;
  32. @synthesize error;
  33. // constructor
  34. - (id)init {
  35. self = [super init];
  36. if(taskQueue == nil) {
  37. taskQueue = [[NSOperationQueue alloc] init];
  38. }
  39. return self;
  40. }
  41. // removing case from headers
  42. + (NSMutableDictionary *) normalizeHeaders:(NSDictionary *)headers {
  43. NSMutableDictionary * mheaders = [[NSMutableDictionary alloc]init];
  44. for(NSString * key in headers) {
  45. [mheaders setValue:[headers valueForKey:key] forKey:[key lowercaseString]];
  46. }
  47. return mheaders;
  48. }
  49. // send HTTP request
  50. - (void) sendRequest:(NSDictionary * _Nullable )options bridge:(RCTBridge * _Nullable)bridgeRef taskId:(NSString * _Nullable)taskId withRequest:(NSURLRequest * _Nullable)req callback:(_Nullable RCTResponseSenderBlock) callback
  51. {
  52. self.taskId = taskId;
  53. self.respData = [[NSMutableData alloc] initWithLength:0];
  54. self.callback = callback;
  55. self.bridge = bridgeRef;
  56. self.expectedBytes = 0;
  57. self.receivedBytes = 0;
  58. self.options = options;
  59. NSString * path = [self.options valueForKey:CONFIG_FILE_PATH];
  60. NSString * ext = [self.options valueForKey:CONFIG_FILE_EXT];
  61. NSURLSession * session;
  62. // the session trust any SSL certification
  63. if([options valueForKey:CONFIG_TRUSTY] != nil)
  64. {
  65. NSURLSessionConfiguration *defaultConfigObject = [NSURLSessionConfiguration defaultSessionConfiguration];
  66. session = [NSURLSession sessionWithConfiguration:defaultConfigObject delegate:self delegateQueue:[NSOperationQueue mainQueue]];
  67. }
  68. // the session validates SSL certification, self-signed certification will be aborted
  69. else
  70. {
  71. session = [NSURLSession sharedSession];
  72. }
  73. // file will be stored at a specific path
  74. if( path != nil) {
  75. // self.fileTaskCompletionHandler = ;
  76. NSURLSessionDownloadTask * task = [session downloadTaskWithRequest:req completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  77. if(error != nil) {
  78. callback(@[[error localizedDescription]]);
  79. return;
  80. }
  81. NSError * taskErr;
  82. NSFileManager * fm = [NSFileManager defaultManager];
  83. // move temp file to desination
  84. [fm moveItemAtURL:location toURL:[NSURL fileURLWithPath:path] error:&taskErr];
  85. if(taskErr != nil) {
  86. callback(@[[taskErr localizedDescription]]);
  87. return;
  88. }
  89. callback(@[[NSNull null], path]);
  90. // prevent memory leaks
  91. self.respData = nil;
  92. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  93. }];
  94. [task resume];
  95. }
  96. // file will be stored at tmp path
  97. else if ( [self.options valueForKey:CONFIG_USE_TEMP]!= nil ) {
  98. // self.fileTaskCompletionHandler;
  99. NSURLSessionDownloadTask * task = [session downloadTaskWithRequest:req completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  100. if(error != nil) {
  101. callback(@[[error localizedDescription]]);
  102. return;
  103. }
  104. NSError * taskErr;
  105. NSFileManager * fm = [NSFileManager defaultManager];
  106. NSString * tmpPath = [RNFetchBlobFS getTempPath:self.taskId withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
  107. // move temp file to desination
  108. [fm moveItemAtURL:location toURL:[NSURL fileURLWithPath:tmpPath] error:&taskErr];
  109. if(taskErr != nil) {
  110. callback(@[[taskErr localizedDescription]]);
  111. return;
  112. }
  113. callback(@[[NSNull null], tmpPath]);
  114. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  115. // prevent memory leaks
  116. self.respData = nil;
  117. }];
  118. [task resume];
  119. }
  120. // base64 response
  121. else {
  122. // self.dataTaskCompletionHandler = ;
  123. NSURLSessionDataTask * task = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable resp, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  124. if(error != nil) {
  125. callback(@[[error localizedDescription]]);
  126. return;
  127. }
  128. else {
  129. callback(@[[NSNull null], [resp base64EncodedStringWithOptions:0]]);
  130. }
  131. self.respData = nil;
  132. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  133. }];
  134. [task resume];
  135. }
  136. // network status indicator
  137. if([[options objectForKey:CONFIG_INDICATOR] boolValue] == YES)
  138. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
  139. }
  140. ////////////////////////////////////////
  141. //
  142. // NSURLSession delegates
  143. //
  144. ////////////////////////////////////////
  145. #pragma mark NSURLSession delegate methods
  146. // set expected content length on response received
  147. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
  148. {
  149. expectedBytes = [response expectedContentLength];
  150. }
  151. // download progress handler
  152. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  153. {
  154. receivedBytes += [data length];
  155. Boolean fileCache = [self.options valueForKey:CONFIG_USE_TEMP];
  156. NSString * path = [self.options valueForKey:CONFIG_FILE_PATH];
  157. // cache data in memory
  158. if(path == nil && fileCache == nil) {
  159. [respData appendData:data];
  160. }
  161. [self.bridge.eventDispatcher
  162. sendDeviceEventWithName:@"RNFetchBlobProgress"
  163. body:@{
  164. @"taskId": taskId,
  165. @"written": [NSString stringWithFormat:@"%d", receivedBytes],
  166. @"total": [NSString stringWithFormat:@"%d", expectedBytes]
  167. }
  168. ];
  169. }
  170. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
  171. NSLog([error localizedDescription]);
  172. self.error = error;
  173. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  174. }
  175. // upload progress handler
  176. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
  177. {
  178. expectedBytes = totalBytesExpectedToWrite;
  179. receivedBytes += totalBytesWritten;
  180. [self.bridge.eventDispatcher
  181. sendDeviceEventWithName:@"RNFetchBlobProgress"
  182. body:@{
  183. @"taskId": taskId,
  184. @"written": [NSString stringWithFormat:@"%d", receivedBytes],
  185. @"total": [NSString stringWithFormat:@"%d", expectedBytes]
  186. }
  187. ];
  188. }
  189. //- (void) application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
  190. //
  191. //}
  192. //- (void) URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
  193. //{
  194. // if(self.dataTaskCompletionHandler != nil)
  195. // {
  196. // dataTaskCompletionHandler(self.respData, nil, error);
  197. // }
  198. // else if(self.fileTaskCompletionHandler != nil)
  199. // {
  200. // fileTaskCompletionHandler(nil, nil, self.error);
  201. // }
  202. //}
  203. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
  204. {
  205. if([options valueForKey:CONFIG_TRUSTY] != nil)
  206. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  207. else {
  208. RCTLogWarn(@"counld not create connection with an unstrusted SSL certification, if you're going to create connection anyway, add `trusty:true` to RNFetchBlob.config");
  209. [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:NO];
  210. }
  211. }
  212. @end