Keine Beschreibung

RNFetchBlob.m 9.8KB

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