No Description

RNFetchBlob.m 9.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253
  1. //
  2. // RNFetchBlob.m
  3. //
  4. // Created by suzuri04x2 on 2016/4/28.
  5. //
  6. #import "RNFetchBlob.h"
  7. #import "RCTConvert.h"
  8. #import "RCTLog.h"
  9. #import <Foundation/Foundation.h>
  10. #import "RCTBridge.h"
  11. #import "RCTEventDispatcher.h"
  12. ////////////////////////////////////////
  13. //
  14. // Util functions
  15. //
  16. ////////////////////////////////////////
  17. @implementation FetchBlobUtils
  18. @synthesize taskId;
  19. @synthesize expectedBytes;
  20. @synthesize receivedBytes;
  21. @synthesize respData;
  22. @synthesize callback;
  23. @synthesize bridge;
  24. // removing case of headers
  25. + (NSMutableDictionary *) normalizeHeaders:(NSDictionary *)headers {
  26. NSMutableDictionary * mheaders = [[NSMutableDictionary alloc]init];
  27. for(NSString * key in headers) {
  28. [mheaders setValue:[headers valueForKey:key] forKey:[key lowercaseString]];
  29. }
  30. return mheaders;
  31. }
  32. - (id)init {
  33. self = [super init];
  34. return self;
  35. }
  36. - (id)delegate:(id)delegate {
  37. return delegate;
  38. }
  39. - (void) sendRequest:(RCTBridge *)bridgeRef taskId:(NSString *)taskId withRequest:(NSURLRequest *)req callback:(RCTResponseSenderBlock) callback {
  40. self.taskId = taskId;
  41. self.respData = [[NSMutableData alloc] initWithLength:0];
  42. self.callback = callback;
  43. self.bridge = bridgeRef;
  44. // Call long-running code on background thread
  45. NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:NO];
  46. [conn scheduleInRunLoop:[NSRunLoop mainRunLoop] forMode:NSRunLoopCommonModes];
  47. [conn start];
  48. if(!conn) {
  49. callback(@[[NSString stringWithFormat:@"RNFetchBlob could not initialize connection"], [NSNull null]]);
  50. }
  51. }
  52. #pragma mark NSURLConnection delegate methods
  53. - (void) connection:(NSURLConnection *)connection didReceiveResponse:(nonnull NSURLResponse *)response {
  54. [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
  55. expectedBytes = [response expectedContentLength];
  56. }
  57. - (void) connection:(NSURLConnection *)connection didReceiveData:(nonnull NSData *)data {
  58. receivedBytes = data.length;
  59. [respData appendData:data];
  60. [self.bridge.eventDispatcher
  61. sendAppEventWithName:@"RNFetchBlobProgress"
  62. body:@{
  63. @"taskId": taskId,
  64. @"written": [NSString stringWithFormat:@"%d", receivedBytes],
  65. @"total": [NSString stringWithFormat:@"%d", expectedBytes]
  66. }
  67. ];
  68. }
  69. - (void) connection:(NSURLConnection *)connection didSendBodyData:(NSInteger)bytesWritten totalBytesWritten:(NSInteger)totalBytesWritten totalBytesExpectedToWrite:(NSInteger)totalBytesExpectedToWrite {
  70. expectedBytes = totalBytesExpectedToWrite;
  71. receivedBytes = totalBytesWritten;
  72. [self.bridge.eventDispatcher
  73. sendAppEventWithName:@"RNFetchBlobProgress"
  74. body:@{
  75. @"taskId": taskId,
  76. @"written": [NSString stringWithFormat:@"%d", receivedBytes],
  77. @"total": [NSString stringWithFormat:@"%d", expectedBytes]
  78. }
  79. ];
  80. }
  81. - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
  82. [UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
  83. callback(@[[error localizedDescription], [NSNull null]]);
  84. }
  85. - (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse: (NSCachedURLResponse *)cachedResponse {
  86. return nil;
  87. }
  88. // handle 301 and 302 responses
  89. - (NSURLRequest *)connection:(NSURLConnection *)connection willSendRequest:(NSURLRequest *)request redirectResponse:response {
  90. return request;
  91. }
  92. // request complete
  93. - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
  94. NSData * data = [NSData dataWithData:respData];
  95. callback(@[[NSNull null], [data base64EncodedStringWithOptions:0]]);
  96. }
  97. @end
  98. ////////////////////////////////////////
  99. //
  100. // Exported native methods
  101. //
  102. ////////////////////////////////////////
  103. @implementation RNFetchBlob
  104. @synthesize bridge = _bridge;
  105. RCT_EXPORT_MODULE();
  106. // Fetch blob data request
  107. RCT_EXPORT_METHOD(fetchBlobForm:(NSString *)taskId method:(NSString *)method url:(NSString *)url headers:(NSDictionary *)headers form:(NSArray *)form callback:(RCTResponseSenderBlock)callback)
  108. {
  109. // send request
  110. NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
  111. initWithURL:[NSURL
  112. URLWithString: url]];
  113. NSMutableDictionary *mheaders = [[NSMutableDictionary alloc] initWithDictionary:[ FetchBlobUtils normalizeHeaders:headers]];
  114. NSTimeInterval timeStamp = [[NSDate date] timeIntervalSince1970];
  115. NSNumber * timeStampObj = [NSNumber numberWithDouble: timeStamp];
  116. // generate boundary
  117. NSString * boundary = [NSString stringWithFormat:@"RNFetchBlob%d", timeStampObj];
  118. // if method is POST or PUT, convert data string format
  119. if([[method lowercaseString] isEqualToString:@"post"] || [[method lowercaseString] isEqualToString:@"put"]) {
  120. NSMutableData * postData = [[NSMutableData alloc] init];
  121. // combine multipart/form-data body
  122. for(id field in form) {
  123. NSString * name = [field valueForKey:@"name"];
  124. NSString * content = [field valueForKey:@"data"];
  125. // field is a text field
  126. if([field valueForKey:@"filename"] == nil) {
  127. [postData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
  128. [postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"\r\n", name] dataUsingEncoding:NSUTF8StringEncoding]];
  129. [postData appendData:[[NSString stringWithFormat:@"Content-Type: text/plain\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
  130. [postData appendData:[[NSString stringWithFormat:@"%@\r\n", content] dataUsingEncoding:NSUTF8StringEncoding]];
  131. }
  132. // field contains a file
  133. else {
  134. NSData* blobData = [[NSData alloc] initWithBase64EncodedString:content options:0];
  135. NSString * filename = [field valueForKey:@"filename"];
  136. [postData appendData:[[NSString stringWithFormat:@"--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
  137. [postData appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"%@\"; filename=\"%@\"\r\n", name, filename] dataUsingEncoding:NSUTF8StringEncoding]];
  138. [postData appendData:[[NSString stringWithFormat:@"Content-Type: application/octet-stream\r\n\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
  139. [postData appendData:blobData];
  140. [postData appendData:[[NSString stringWithFormat:@"\r\n"] dataUsingEncoding:NSUTF8StringEncoding]];
  141. }
  142. }
  143. // close form data
  144. [postData appendData: [[NSString stringWithFormat:@"--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
  145. [request setHTTPBody:postData];
  146. // set content-length
  147. [mheaders setValue:[NSString stringWithFormat:@"%d",[postData length]] forKey:@"Content-Length"];
  148. [mheaders setValue:[NSString stringWithFormat:@"100-continue",[postData length]] forKey:@"Expect"];
  149. // appaned boundary to content-type
  150. [mheaders setValue:[NSString stringWithFormat:@"multipart/form-data; charset=utf-8; boundary=%@", boundary] forKey:@"content-type"];
  151. }
  152. [request setHTTPMethod: method];
  153. [request setAllHTTPHeaderFields:mheaders];
  154. [[[FetchBlobUtils alloc] init] sendRequest:self.bridge taskId:taskId withRequest:request callback:callback];
  155. // create thread for http request
  156. // NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  157. // [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
  158. //
  159. // [FetchBlobUtils onBlobResponse:response withData:data withError: connectionError withCallback: callback];
  160. //
  161. // }];
  162. }
  163. // Fetch blob data request
  164. RCT_EXPORT_METHOD(fetchBlob:(NSString *)taskId method:(NSString *)method url:(NSString *)url headers:(NSDictionary *)headers body:(NSString *)body callback:(RCTResponseSenderBlock)callback)
  165. {
  166. // send request
  167. NSMutableURLRequest *request = [[NSMutableURLRequest alloc]
  168. initWithURL:[NSURL
  169. URLWithString: url]];
  170. NSMutableDictionary *mheaders = [[NSMutableDictionary alloc] initWithDictionary:[FetchBlobUtils normalizeHeaders:headers]];
  171. // if method is POST or PUT, convert data string format
  172. if([[method lowercaseString] isEqualToString:@"post"] || [[method lowercaseString] isEqualToString:@"put"]) {
  173. // generate octet-stream body
  174. NSData* blobData = [[NSData alloc] initWithBase64EncodedString:body options:0];
  175. NSMutableData* postBody = [[NSMutableData alloc] init];
  176. [postBody appendData:[NSData dataWithData:blobData]];
  177. [request setHTTPBody:postBody];
  178. [mheaders setValue:@"application/octet-stream" forKey:@"content-type"];
  179. }
  180. [request setHTTPMethod: method];
  181. [request setAllHTTPHeaderFields:mheaders];
  182. [[[FetchBlobUtils alloc] init] sendRequest:self.bridge taskId:taskId withRequest:request callback:callback];
  183. // create thread for http request
  184. // NSOperationQueue *queue = [[NSOperationQueue alloc] init];
  185. //
  186. //
  187. // [NSURLConnection sendAsynchronousRequest:request queue:queue completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
  188. //
  189. // [FetchBlobUtils onBlobResponse:response withData:data withError: connectionError withCallback: callback];
  190. //
  191. // }];
  192. }
  193. @end