Bez popisu

RNFetchBlob.m 23KB

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