Aucune description

RNFetchBlobNetwork.m 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232
  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:taskQueue];
  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. }];
  93. [task resume];
  94. }
  95. // file will be stored at tmp path
  96. else if ( [self.options valueForKey:CONFIG_USE_TEMP]!= nil ) {
  97. // self.fileTaskCompletionHandler;
  98. NSURLSessionDownloadTask * task = [session downloadTaskWithRequest:req completionHandler:^(NSURL * _Nullable location, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  99. if(error != nil) {
  100. callback(@[[error localizedDescription]]);
  101. return;
  102. }
  103. NSError * taskErr;
  104. NSFileManager * fm = [NSFileManager defaultManager];
  105. NSString * tmpPath = [RNFetchBlobFS getTempPath:self.taskId withExtension:[self.options valueForKey:CONFIG_FILE_EXT]];
  106. // move temp file to desination
  107. [fm moveItemAtURL:location toURL:[NSURL fileURLWithPath:tmpPath] error:&taskErr];
  108. if(taskErr != nil) {
  109. callback(@[[taskErr localizedDescription]]);
  110. return;
  111. }
  112. callback(@[[NSNull null], tmpPath]);
  113. // prevent memory leaks
  114. self.respData = nil;
  115. }];
  116. [task resume];
  117. }
  118. // base64 response
  119. else {
  120. // self.dataTaskCompletionHandler = ;
  121. NSURLSessionDataTask * task = [session dataTaskWithRequest:req completionHandler:^(NSData * _Nullable resp, NSURLResponse * _Nullable response, NSError * _Nullable error) {
  122. if(error != nil) {
  123. callback(@[[error localizedDescription]]);
  124. return;
  125. }
  126. else {
  127. callback(@[[NSNull null], [resp base64EncodedStringWithOptions:0]]);
  128. }
  129. }];
  130. [task resume];
  131. }
  132. }
  133. ////////////////////////////////////////
  134. //
  135. // NSURLSession delegates
  136. //
  137. ////////////////////////////////////////
  138. #pragma mark NSURLSession delegate methods
  139. // set expected content length on response received
  140. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveResponse:(NSURLResponse *)response completionHandler:(void (^)(NSURLSessionResponseDisposition))completionHandler
  141. {
  142. expectedBytes = [response expectedContentLength];
  143. }
  144. // download progress handler
  145. - (void) URLSession:(NSURLSession *)session dataTask:(NSURLSessionDataTask *)dataTask didReceiveData:(NSData *)data
  146. {
  147. receivedBytes += [data length];
  148. Boolean fileCache = [self.options valueForKey:CONFIG_USE_TEMP];
  149. NSString * path = [self.options valueForKey:CONFIG_FILE_PATH];
  150. // cache data in memory
  151. if(path == nil && fileCache == nil) {
  152. [respData appendData:data];
  153. }
  154. [self.bridge.eventDispatcher
  155. sendDeviceEventWithName:@"RNFetchBlobProgress"
  156. body:@{
  157. @"taskId": taskId,
  158. @"written": [NSString stringWithFormat:@"%d", receivedBytes],
  159. @"total": [NSString stringWithFormat:@"%d", expectedBytes]
  160. }
  161. ];
  162. }
  163. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didCompleteWithError:(NSError *)error {
  164. NSLog([error localizedDescription]);
  165. self.error = error;
  166. }
  167. // upload progress handler
  168. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didSendBodyData:(int64_t)bytesSent totalBytesSent:(int64_t)totalBytesWritten totalBytesExpectedToSend:(int64_t)totalBytesExpectedToWrite
  169. {
  170. expectedBytes = totalBytesExpectedToWrite;
  171. receivedBytes += totalBytesWritten;
  172. [self.bridge.eventDispatcher
  173. sendDeviceEventWithName:@"RNFetchBlobProgress"
  174. body:@{
  175. @"taskId": taskId,
  176. @"written": [NSString stringWithFormat:@"%d", receivedBytes],
  177. @"total": [NSString stringWithFormat:@"%d", expectedBytes]
  178. }
  179. ];
  180. }
  181. - (void) application:(UIApplication *)application handleEventsForBackgroundURLSession:(NSString *)identifier completionHandler:(void (^)())completionHandler {
  182. }
  183. //- (void) URLSessionDidFinishEventsForBackgroundURLSession:(NSURLSession *)session
  184. //{
  185. // if(self.dataTaskCompletionHandler != nil)
  186. // {
  187. // dataTaskCompletionHandler(self.respData, nil, error);
  188. // }
  189. // else if(self.fileTaskCompletionHandler != nil)
  190. // {
  191. // fileTaskCompletionHandler(nil, nil, self.error);
  192. // }
  193. //}
  194. - (void) URLSession:(NSURLSession *)session task:(NSURLSessionTask *)task didReceiveChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition, NSURLCredential * _Nullable))completionHandler
  195. {
  196. if([options valueForKey:CONFIG_TRUSTY] != nil)
  197. completionHandler(NSURLSessionAuthChallengeUseCredential, [NSURLCredential credentialForTrust:challenge.protectionSpace.serverTrust]);
  198. else
  199. RCTLogWarn(@"counld not create connection with an unstrusted SSL certification, if you're going to create connection anyway, add `trusty:true` to RNFetchBlob.config");
  200. }
  201. @end