No Description

RNFetchBlob.m 22KB

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