No Description

RNFetchBlob.m 23KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639
  1. //
  2. // RNFetchBlob.m
  3. //
  4. // Created by wkh237 on 2016/4/28.
  5. //
  6. #import "RNFetchBlob.h"
  7. #import "RNFetchBlobFS.h"
  8. #import "RNFetchBlobNetwork.h"
  9. #import "RNFetchBlobConst.h"
  10. #import "RNFetchBlobReqBuilder.h"
  11. #import "RNFetchBlobProgress.h"
  12. __strong RCTBridge * bridgeRef;
  13. dispatch_queue_t commonTaskQueue;
  14. dispatch_queue_t fsQueue;
  15. ////////////////////////////////////////
  16. //
  17. // Exported native methods
  18. //
  19. ////////////////////////////////////////
  20. #pragma mark RNFetchBlob exported methods
  21. @implementation RNFetchBlob
  22. @synthesize filePathPrefix;
  23. @synthesize documentController;
  24. @synthesize bridge = _bridge;
  25. - (dispatch_queue_t) methodQueue {
  26. if(commonTaskQueue == nil)
  27. commonTaskQueue = dispatch_queue_create("RNFetchBlob.queue", DISPATCH_QUEUE_SERIAL);
  28. return commonTaskQueue;
  29. }
  30. + (RCTBridge *)getRCTBridge
  31. {
  32. RCTRootView * rootView = (RCTRootView*) [[UIApplication sharedApplication] keyWindow].rootViewController.view;
  33. return rootView.bridge;
  34. }
  35. + (BOOL)requiresMainQueueSetup {
  36. return NO;
  37. }
  38. RCT_EXPORT_MODULE();
  39. - (id) init {
  40. self = [super init];
  41. self.filePathPrefix = FILE_PREFIX;
  42. if(commonTaskQueue == nil)
  43. commonTaskQueue = dispatch_queue_create("RNFetchBlob.queue", DISPATCH_QUEUE_SERIAL);
  44. if(fsQueue == nil)
  45. fsQueue = dispatch_queue_create("RNFetchBlob.fs.queue", DISPATCH_QUEUE_SERIAL);
  46. BOOL isDir;
  47. // if temp folder not exists, create one
  48. if(![[NSFileManager defaultManager] fileExistsAtPath: [RNFetchBlobFS getTempPath] isDirectory:&isDir]) {
  49. [[NSFileManager defaultManager] createDirectoryAtPath:[RNFetchBlobFS getTempPath] withIntermediateDirectories:YES attributes:nil error:NULL];
  50. }
  51. bridgeRef = _bridge;
  52. [RNFetchBlobNetwork emitExpiredTasks];
  53. return self;
  54. }
  55. - (NSDictionary *)constantsToExport
  56. {
  57. return @{
  58. @"MainBundleDir" : [RNFetchBlobFS getMainBundleDir],
  59. @"DocumentDir": [RNFetchBlobFS getDocumentDir],
  60. @"CacheDir" : [RNFetchBlobFS getCacheDir]
  61. };
  62. }
  63. // Fetch blob data request
  64. RCT_EXPORT_METHOD(fetchBlobForm:(NSDictionary *)options
  65. taskId:(NSString *)taskId
  66. method:(NSString *)method
  67. url:(NSString *)url
  68. headers:(NSDictionary *)headers
  69. form:(NSArray *)form
  70. callback:(RCTResponseSenderBlock)callback)
  71. {
  72. [RNFetchBlobReqBuilder buildMultipartRequest:options
  73. taskId:taskId
  74. method:method
  75. url:url
  76. headers:headers
  77. form:form
  78. onComplete:^(__weak NSURLRequest *req, long bodyLength)
  79. {
  80. // something went wrong when building the request body
  81. if(req == nil)
  82. {
  83. callback(@[@"RNFetchBlob.fetchBlobForm failed to create request body"]);
  84. }
  85. // send HTTP request
  86. else
  87. {
  88. [[RNFetchBlobNetwork sharedInstance] sendRequest:options
  89. contentLength:bodyLength
  90. bridge:self.bridge
  91. taskId:taskId
  92. withRequest:req
  93. callback:callback];
  94. }
  95. }];
  96. }
  97. // Fetch blob data request
  98. RCT_EXPORT_METHOD(fetchBlob:(NSDictionary *)options
  99. taskId:(NSString *)taskId
  100. method:(NSString *)method
  101. url:(NSString *)url
  102. headers:(NSDictionary *)headers
  103. body:(NSString *)body callback:(RCTResponseSenderBlock)callback)
  104. {
  105. [RNFetchBlobReqBuilder buildOctetRequest:options
  106. taskId:taskId
  107. method:method
  108. url:url
  109. headers:headers
  110. body:body
  111. onComplete:^(NSURLRequest *req, long bodyLength)
  112. {
  113. // something went wrong when building the request body
  114. if(req == nil)
  115. {
  116. callback(@[@"RNFetchBlob.fetchBlob failed to create request body"]);
  117. }
  118. // send HTTP request
  119. else
  120. {
  121. [[RNFetchBlobNetwork sharedInstance] sendRequest:options
  122. contentLength:bodyLength
  123. bridge:self.bridge
  124. taskId:taskId
  125. withRequest:req
  126. callback:callback];
  127. }
  128. }];
  129. }
  130. #pragma mark - fs.createFile
  131. RCT_EXPORT_METHOD(createFile:(NSString *)path
  132. data:(NSString *)data
  133. encoding:(NSString *)encoding
  134. resolver:(RCTPromiseResolveBlock)resolve
  135. rejecter:(RCTPromiseRejectBlock)reject)
  136. {
  137. NSFileManager * fm = [NSFileManager defaultManager];
  138. NSData * fileContent = nil;
  139. if([[encoding lowercaseString] isEqualToString:@"utf8"]) {
  140. fileContent = [[NSData alloc] initWithData:[data dataUsingEncoding:NSUTF8StringEncoding allowLossyConversion:YES]];
  141. }
  142. else if([[encoding lowercaseString] isEqualToString:@"base64"]) {
  143. fileContent = [[NSData alloc] initWithBase64EncodedData:data options:0];
  144. }
  145. else if([[encoding lowercaseString] isEqualToString:@"uri"]) {
  146. NSString * orgPath = [data stringByReplacingOccurrencesOfString:FILE_PREFIX withString:@""];
  147. fileContent = [[NSData alloc] initWithContentsOfFile:orgPath];
  148. }
  149. else {
  150. fileContent = [[NSData alloc] initWithData:[data dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]];
  151. }
  152. if ([fm fileExistsAtPath:path]) {
  153. reject(@"EEXIST", [NSString stringWithFormat:@"File '%@' already exists", path], nil);
  154. }
  155. else {
  156. BOOL success = [fm createFileAtPath:path contents:fileContent attributes:NULL];
  157. if(success == YES)
  158. resolve(@[[NSNull null]]);
  159. else
  160. reject(@"EUNSPECIFIED", [NSString stringWithFormat:@"Failed to create new file at path '%@', please ensure the folder exists", path], nil);
  161. }
  162. }
  163. #pragma mark - fs.createFileASCII
  164. // method for create file with ASCII content
  165. RCT_EXPORT_METHOD(createFileASCII:(NSString *)path
  166. data:(NSArray *)dataArray
  167. resolver:(RCTPromiseResolveBlock)resolve
  168. rejecter:(RCTPromiseRejectBlock)reject)
  169. {
  170. NSFileManager * fm = [NSFileManager defaultManager];
  171. NSMutableData * fileContent = [NSMutableData alloc];
  172. // prevent stack overflow, alloc on heap
  173. char * bytes = (char*) malloc([dataArray count]);
  174. for(int i = 0; i < dataArray.count; i++) {
  175. bytes[i] = [[dataArray objectAtIndex:i] charValue];
  176. }
  177. [fileContent appendBytes:bytes length:dataArray.count];
  178. if ([fm fileExistsAtPath:path]) {
  179. reject(@"EEXIST", [NSString stringWithFormat:@"File '%@' already exists", path], nil);
  180. }
  181. else {
  182. BOOL success = [fm createFileAtPath:path contents:fileContent attributes:NULL];
  183. if(success == YES)
  184. resolve(@[[NSNull null]]);
  185. else
  186. reject(@"EUNSPECIFIED", [NSString stringWithFormat:@"failed to create new file at path '%@', please ensure the folder exists", path], nil);
  187. }
  188. free(bytes);
  189. }
  190. #pragma mark - fs.pathForAppGroup
  191. RCT_EXPORT_METHOD(pathForAppGroup:(NSString *)groupName
  192. resolver:(RCTPromiseResolveBlock)resolve
  193. rejecter:(RCTPromiseRejectBlock)reject)
  194. {
  195. NSString * path = [RNFetchBlobFS getPathForAppGroup:groupName];
  196. if(path) {
  197. resolve(path);
  198. } else {
  199. reject(@"EUNSPECIFIED", @"could not find path for app group", nil);
  200. }
  201. }
  202. #pragma mark - fs.exists
  203. RCT_EXPORT_METHOD(exists:(NSString *)path callback:(RCTResponseSenderBlock)callback) {
  204. [RNFetchBlobFS exists:path callback:callback];
  205. }
  206. #pragma mark - fs.writeFile
  207. RCT_EXPORT_METHOD(writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  208. {
  209. [RNFetchBlobFS writeFile:path encoding:[NSString stringWithString:encoding] data:data append:append resolver:resolve rejecter:reject];
  210. }
  211. #pragma mark - fs.writeArray
  212. RCT_EXPORT_METHOD(writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  213. {
  214. [RNFetchBlobFS writeFileArray:path data:data append:append resolver:resolve rejecter:reject];
  215. }
  216. #pragma mark - fs.writeStream
  217. RCT_EXPORT_METHOD(writeStream:(NSString *)path withEncoding:(NSString *)encoding appendData:(BOOL)append callback:(RCTResponseSenderBlock)callback)
  218. {
  219. RNFetchBlobFS * fileStream = [[RNFetchBlobFS alloc] initWithBridgeRef:self.bridge];
  220. NSFileManager * fm = [NSFileManager defaultManager];
  221. NSString * folder = [path stringByDeletingLastPathComponent];
  222. NSError* err = nil;
  223. BOOL isDir = NO;
  224. BOOL exists = [fm fileExistsAtPath:path isDirectory: &isDir];
  225. if(!exists) {
  226. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:&err];
  227. if(err != nil) {
  228. callback(@[@"ENOTDIR", [NSString stringWithFormat:@"Failed to create parent directory of '%@'; error: %@", path, [err description]]]);
  229. }
  230. if(![fm createFileAtPath:path contents:nil attributes:nil]) {
  231. callback(@[@"ENOENT", [NSString stringWithFormat:@"File '%@' does not exist and could not be created", path]]);
  232. }
  233. }
  234. else if(isDir) {
  235. callback(@[@"EISDIR", [NSString stringWithFormat:@"Expecting a file but '%@' is a directory", path]]);
  236. }
  237. NSString * streamId = [fileStream openWithPath:path encode:encoding appendData:append];
  238. callback(@[[NSNull null], [NSNull null], streamId]);
  239. }
  240. #pragma mark - fs.writeArrayChunk
  241. RCT_EXPORT_METHOD(writeArrayChunk:(NSString *)streamId withArray:(NSArray *)dataArray callback:(RCTResponseSenderBlock) callback)
  242. {
  243. RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
  244. char * bytes = (char *) malloc([dataArray count]);
  245. for(int i = 0; i < dataArray.count; i++) {
  246. bytes[i] = [[dataArray objectAtIndex:i] charValue];
  247. }
  248. NSMutableData * data = [NSMutableData alloc];
  249. [data appendBytes:bytes length:dataArray.count];
  250. [fs write:data];
  251. free(bytes);
  252. callback(@[[NSNull null]]);
  253. }
  254. #pragma mark - fs.writeChunk
  255. RCT_EXPORT_METHOD(writeChunk:(NSString *)streamId withData:(NSString *)data callback:(RCTResponseSenderBlock) callback)
  256. {
  257. RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
  258. [fs writeEncodeChunk:data];
  259. callback(@[[NSNull null]]);
  260. }
  261. #pragma mark - fs.closeStream
  262. RCT_EXPORT_METHOD(closeStream:(NSString *)streamId callback:(RCTResponseSenderBlock) callback)
  263. {
  264. RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
  265. [fs closeOutStream];
  266. callback(@[[NSNull null], @YES]);
  267. }
  268. #pragma mark - unlink
  269. RCT_EXPORT_METHOD(unlink:(NSString *)path callback:(RCTResponseSenderBlock) callback)
  270. {
  271. NSError * error = nil;
  272. NSString * tmpPath = nil;
  273. [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
  274. if(error == nil || [[NSFileManager defaultManager] fileExistsAtPath:path] == NO)
  275. callback(@[[NSNull null]]);
  276. else
  277. callback(@[[NSString stringWithFormat:@"failed to unlink file or path at %@", path]]);
  278. }
  279. #pragma mark - fs.removeSession
  280. RCT_EXPORT_METHOD(removeSession:(NSArray *)paths callback:(RCTResponseSenderBlock) callback)
  281. {
  282. NSError * error = nil;
  283. NSString * tmpPath = nil;
  284. for(NSString * path in paths) {
  285. [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
  286. if(error != nil) {
  287. callback(@[[NSString stringWithFormat:@"failed to remove session path at %@", path]]);
  288. return;
  289. }
  290. }
  291. callback(@[[NSNull null]]);
  292. }
  293. #pragma mark - fs.ls
  294. RCT_EXPORT_METHOD(ls:(NSString *)path resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  295. {
  296. NSFileManager* fm = [NSFileManager defaultManager];
  297. BOOL exist = nil;
  298. BOOL isDir = nil;
  299. exist = [fm fileExistsAtPath:path isDirectory:&isDir];
  300. if(exist == NO) {
  301. return reject(@"ENOENT", [NSString stringWithFormat:@"No such file '%@'", path], nil);
  302. }
  303. if(isDir == NO) {
  304. return reject(@"ENOTDIR", [NSString stringWithFormat:@"Not a directory '%@'", path], nil);
  305. }
  306. NSError * error = nil;
  307. NSArray * result = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
  308. if(error == nil)
  309. resolve(result);
  310. else
  311. reject(@"EUNSPECIFIED", [error description], nil);
  312. }
  313. #pragma mark - fs.stat
  314. RCT_EXPORT_METHOD(stat:(NSString *)target callback:(RCTResponseSenderBlock) callback)
  315. {
  316. [RNFetchBlobFS getPathFromUri:target completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  317. __block NSMutableArray * result;
  318. if(path != nil)
  319. {
  320. NSFileManager* fm = [NSFileManager defaultManager];
  321. BOOL exist = nil;
  322. BOOL isDir = nil;
  323. NSError * error = nil;
  324. exist = [fm fileExistsAtPath:path isDirectory:&isDir];
  325. if(exist == NO) {
  326. callback(@[[NSString stringWithFormat:@"failed to stat path `%@` because it does not exist or it is not a folder", path]]);
  327. return ;
  328. }
  329. result = [RNFetchBlobFS stat:path error:&error];
  330. if(error == nil)
  331. callback(@[[NSNull null], result]);
  332. else
  333. callback(@[[error localizedDescription], [NSNull null]]);
  334. }
  335. else if(asset != nil)
  336. {
  337. __block NSNumber * size = [NSNumber numberWithLong:[asset size]];
  338. result = [asset metadata];
  339. [result setValue:size forKey:@"size"];
  340. callback(@[[NSNull null], result]);
  341. }
  342. else
  343. {
  344. callback(@[@"failed to stat path, could not resolve URI", [NSNull null]]);
  345. }
  346. }];
  347. }
  348. #pragma mark - fs.lstat
  349. RCT_EXPORT_METHOD(lstat:(NSString *)path callback:(RCTResponseSenderBlock) callback)
  350. {
  351. NSFileManager* fm = [NSFileManager defaultManager];
  352. BOOL exist = nil;
  353. BOOL isDir = nil;
  354. path = [RNFetchBlobFS getPathOfAsset:path];
  355. exist = [fm fileExistsAtPath:path isDirectory:&isDir];
  356. if(exist == NO) {
  357. callback(@[[NSString stringWithFormat:@"failed to lstat path `%@` because it does not exist or it is not a folder", path]]);
  358. return ;
  359. }
  360. NSError * error = nil;
  361. NSArray * files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
  362. NSMutableArray * res = [[NSMutableArray alloc] init];
  363. if(isDir == YES) {
  364. for(NSString * p in files) {
  365. NSString * filePath = [NSString stringWithFormat:@"%@/%@", path, p];
  366. [res addObject:[RNFetchBlobFS stat:filePath error:&error]];
  367. }
  368. }
  369. else {
  370. [res addObject:[RNFetchBlobFS stat:path error:&error]];
  371. }
  372. if(error == nil)
  373. callback(@[[NSNull null], res == nil ? [NSNull null] :res ]);
  374. else
  375. callback(@[[error localizedDescription], [NSNull null]]);
  376. }
  377. #pragma mark - fs.cp
  378. RCT_EXPORT_METHOD(cp:(NSString*)src toPath:(NSString *)dest callback:(RCTResponseSenderBlock) callback)
  379. {
  380. // path = [RNFetchBlobFS getPathOfAsset:path];
  381. [RNFetchBlobFS getPathFromUri:src completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  382. NSError * error = nil;
  383. if(path == nil)
  384. {
  385. [RNFetchBlobFS writeAssetToPath:asset dest:dest];
  386. callback(@[[NSNull null], @YES]);
  387. }
  388. else
  389. {
  390. // If the destination exists there will be an error
  391. BOOL result = [[NSFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:path] toURL:[NSURL fileURLWithPath:dest] error:&error];
  392. if(error == nil)
  393. callback(@[[NSNull null], @YES]);
  394. else
  395. callback(@[[error localizedDescription], @NO]);
  396. }
  397. }];
  398. }
  399. #pragma mark - fs.mv
  400. RCT_EXPORT_METHOD(mv:(NSString *)path toPath:(NSString *)dest callback:(RCTResponseSenderBlock) callback)
  401. {
  402. NSError * error = nil;
  403. BOOL result = [[NSFileManager defaultManager] moveItemAtURL:[NSURL fileURLWithPath:path] toURL:[NSURL fileURLWithPath:dest] error:&error];
  404. if(error == nil)
  405. callback(@[[NSNull null], @YES]);
  406. else
  407. callback(@[[error localizedDescription], @NO]);
  408. }
  409. #pragma mark - fs.mkdir
  410. RCT_EXPORT_METHOD(mkdir:(NSString *)path resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  411. {
  412. [RNFetchBlobFS mkdir:path resolver:resolve rejecter:reject];
  413. }
  414. #pragma mark - fs.readFile
  415. RCT_EXPORT_METHOD(readFile:(NSString *)path
  416. encoding:(NSString *)encoding
  417. resolver:(RCTPromiseResolveBlock)resolve
  418. rejecter:(RCTPromiseRejectBlock)reject)
  419. {
  420. [RNFetchBlobFS readFile:path encoding:encoding onComplete:^(NSData * content, NSString * code, NSString * err) {
  421. if(err != nil) {
  422. reject(code, err, nil);
  423. return;
  424. }
  425. if(encoding == @"ascii") {
  426. resolve((NSMutableArray *)content);
  427. }
  428. else {
  429. resolve((NSString *)content);
  430. }
  431. }];
  432. }
  433. #pragma mark - fs.hash
  434. RCT_EXPORT_METHOD(hash:(NSString *)path
  435. algorithm:(NSString *)algorithm
  436. resolver:(RCTPromiseResolveBlock)resolve
  437. rejecter:(RCTPromiseRejectBlock)reject)
  438. {
  439. [RNFetchBlobFS hash:path algorithm:[NSString stringWithString:algorithm] resolver:resolve rejecter:reject];
  440. }
  441. #pragma mark - fs.readStream
  442. RCT_EXPORT_METHOD(readStream:(NSString *)path withEncoding:(NSString *)encoding bufferSize:(int)bufferSize tick:(int)tick streamId:(NSString *)streamId)
  443. {
  444. if(bufferSize == nil) {
  445. if([[encoding lowercaseString] isEqualToString:@"base64"])
  446. bufferSize = 4095;
  447. else
  448. bufferSize = 4096;
  449. }
  450. dispatch_async(fsQueue, ^{
  451. [RNFetchBlobFS readStream:path encoding:encoding bufferSize:bufferSize tick:tick streamId:streamId bridgeRef:_bridge];
  452. });
  453. }
  454. #pragma mark - fs.getEnvionmentDirs
  455. RCT_EXPORT_METHOD(getEnvironmentDirs:(RCTResponseSenderBlock) callback)
  456. {
  457. callback(@[
  458. [RNFetchBlobFS getDocumentDir],
  459. [RNFetchBlobFS getCacheDir],
  460. ]);
  461. }
  462. #pragma mark - net.cancelRequest
  463. RCT_EXPORT_METHOD(cancelRequest:(NSString *)taskId callback:(RCTResponseSenderBlock)callback) {
  464. [[RNFetchBlobNetwork sharedInstance] cancelRequest:taskId];
  465. callback(@[[NSNull null], taskId]);
  466. }
  467. #pragma mark - net.enableProgressReport
  468. RCT_EXPORT_METHOD(enableProgressReport:(NSString *)taskId interval:(nonnull NSNumber*)interval count:(nonnull NSNumber*)count)
  469. {
  470. RNFetchBlobProgress * cfg = [[RNFetchBlobProgress alloc] initWithType:Download interval:interval count:count];
  471. [[RNFetchBlobNetwork sharedInstance] enableProgressReport:taskId config:cfg];
  472. }
  473. #pragma mark - net.enableUploadProgressReport
  474. RCT_EXPORT_METHOD(enableUploadProgressReport:(NSString *)taskId interval:(nonnull NSNumber*)interval count:(nonnull NSNumber*)count)
  475. {
  476. RNFetchBlobProgress * cfg = [[RNFetchBlobProgress alloc] initWithType:Upload interval:interval count:count];
  477. [[RNFetchBlobNetwork sharedInstance] enableUploadProgress:taskId config:cfg];
  478. }
  479. #pragma mark - fs.slice
  480. RCT_EXPORT_METHOD(slice:(NSString *)src dest:(NSString *)dest start:(nonnull NSNumber *)start end:(nonnull NSNumber *)end resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  481. {
  482. [RNFetchBlobFS slice:src dest:dest start:start end:end encode:@"" resolver:resolve rejecter:reject];
  483. }
  484. RCT_EXPORT_METHOD(previewDocument:(NSString*)uri scheme:(NSString *)scheme resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  485. {
  486. NSString * utf8uri = [uri stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  487. NSURL * url = [[NSURL alloc] initWithString:utf8uri];
  488. // NSURL * url = [[NSURL alloc] initWithString:uri];
  489. documentController = [UIDocumentInteractionController interactionControllerWithURL:url];
  490. UIViewController *rootCtrl = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
  491. documentController.delegate = self;
  492. if(scheme == nil || [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:scheme]]) {
  493. CGRect rect = CGRectMake(0.0, 0.0, 0.0, 0.0);
  494. dispatch_sync(dispatch_get_main_queue(), ^{
  495. [documentController presentOptionsMenuFromRect:rect inView:rootCtrl.view animated:YES];
  496. });
  497. resolve(@[[NSNull null]]);
  498. } else {
  499. reject(@"EINVAL", @"scheme is not supported", nil);
  500. }
  501. }
  502. # pragma mark - open file with UIDocumentInteractionController and delegate
  503. RCT_EXPORT_METHOD(openDocument:(NSString*)uri scheme:(NSString *)scheme resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  504. {
  505. NSString * utf8uri = [uri stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  506. NSURL * url = [[NSURL alloc] initWithString:utf8uri];
  507. // NSURL * url = [[NSURL alloc] initWithString:uri];
  508. documentController = [UIDocumentInteractionController interactionControllerWithURL:url];
  509. documentController.delegate = self;
  510. if(scheme == nil || [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:scheme]]) {
  511. dispatch_sync(dispatch_get_main_queue(), ^{
  512. if([documentController presentPreviewAnimated:YES]) {
  513. resolve(@[[NSNull null]]);
  514. } else {
  515. reject(@"EINVAL", @"document is not supported", nil);
  516. }
  517. });
  518. } else {
  519. reject(@"EINVAL", @"scheme is not supported", nil);
  520. }
  521. }
  522. # pragma mark - exclude from backup key
  523. RCT_EXPORT_METHOD(excludeFromBackupKey:(NSString *)url resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  524. {
  525. NSError *error = nil;
  526. [ [NSURL URLWithString:url] setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&error];
  527. if(!error)
  528. {
  529. resolve(@[[NSNull null]]);
  530. } else {
  531. reject(@"EUNSPECIFIED", [error description], nil);
  532. }
  533. }
  534. RCT_EXPORT_METHOD(df:(RCTResponseSenderBlock)callback)
  535. {
  536. [RNFetchBlobFS df:callback];
  537. }
  538. - (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller
  539. {
  540. UIWindow *window = [UIApplication sharedApplication].keyWindow;
  541. return window.rootViewController;
  542. }
  543. # pragma mark - check expired network events
  544. RCT_EXPORT_METHOD(emitExpiredEvent:(RCTResponseSenderBlock)callback)
  545. {
  546. [RNFetchBlobNetwork emitExpiredTasks];
  547. }
  548. @end