Няма описание

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656
  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.syncPathAppGroup
  208. RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(syncPathAppGroup:(NSString *)groupName) {
  209. NSURL *pathUrl = [[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:groupName];
  210. NSString *path = [pathUrl path];
  211. if(path) {
  212. return path;
  213. } else {
  214. return @"";
  215. }
  216. }
  217. #pragma mark - fs.exists
  218. RCT_EXPORT_METHOD(exists:(NSString *)path callback:(RCTResponseSenderBlock)callback) {
  219. [RNFetchBlobFS exists:path callback:callback];
  220. }
  221. #pragma mark - fs.writeFile
  222. RCT_EXPORT_METHOD(writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  223. {
  224. [RNFetchBlobFS writeFile:path encoding:[NSString stringWithString:encoding] data:data append:append resolver:resolve rejecter:reject];
  225. }
  226. #pragma mark - fs.writeArray
  227. RCT_EXPORT_METHOD(writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  228. {
  229. [RNFetchBlobFS writeFileArray:path data:data append:append resolver:resolve rejecter:reject];
  230. }
  231. #pragma mark - fs.writeStream
  232. RCT_EXPORT_METHOD(writeStream:(NSString *)path withEncoding:(NSString *)encoding appendData:(BOOL)append callback:(RCTResponseSenderBlock)callback)
  233. {
  234. RNFetchBlobFS * fileStream = [[RNFetchBlobFS alloc] initWithBridgeRef:self.bridge];
  235. NSFileManager * fm = [NSFileManager defaultManager];
  236. NSString * folder = [path stringByDeletingLastPathComponent];
  237. NSError* err = nil;
  238. BOOL isDir = NO;
  239. BOOL exists = [fm fileExistsAtPath:path isDirectory: &isDir];
  240. if(!exists) {
  241. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:&err];
  242. if(err != nil) {
  243. callback(@[@"ENOTDIR", [NSString stringWithFormat:@"Failed to create parent directory of '%@'; error: %@", path, [err description]]]);
  244. }
  245. if(![fm createFileAtPath:path contents:nil attributes:nil]) {
  246. callback(@[@"ENOENT", [NSString stringWithFormat:@"File '%@' does not exist and could not be created", path]]);
  247. }
  248. }
  249. else if(isDir) {
  250. callback(@[@"EISDIR", [NSString stringWithFormat:@"Expecting a file but '%@' is a directory", path]]);
  251. }
  252. NSString * streamId = [fileStream openWithPath:path encode:encoding appendData:append];
  253. callback(@[[NSNull null], [NSNull null], streamId]);
  254. }
  255. #pragma mark - fs.writeArrayChunk
  256. RCT_EXPORT_METHOD(writeArrayChunk:(NSString *)streamId withArray:(NSArray *)dataArray callback:(RCTResponseSenderBlock) callback)
  257. {
  258. RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
  259. char * bytes = (char *) malloc([dataArray count]);
  260. for(int i = 0; i < dataArray.count; i++) {
  261. bytes[i] = [[dataArray objectAtIndex:i] charValue];
  262. }
  263. NSMutableData * data = [NSMutableData alloc];
  264. [data appendBytes:bytes length:dataArray.count];
  265. [fs write:data];
  266. free(bytes);
  267. callback(@[[NSNull null]]);
  268. }
  269. #pragma mark - fs.writeChunk
  270. RCT_EXPORT_METHOD(writeChunk:(NSString *)streamId withData:(NSString *)data callback:(RCTResponseSenderBlock) callback)
  271. {
  272. RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
  273. [fs writeEncodeChunk:data];
  274. callback(@[[NSNull null]]);
  275. }
  276. #pragma mark - fs.closeStream
  277. RCT_EXPORT_METHOD(closeStream:(NSString *)streamId callback:(RCTResponseSenderBlock) callback)
  278. {
  279. RNFetchBlobFS *fs = [[RNFetchBlobFS getFileStreams] valueForKey:streamId];
  280. [fs closeOutStream];
  281. callback(@[[NSNull null], @YES]);
  282. }
  283. #pragma mark - unlink
  284. RCT_EXPORT_METHOD(unlink:(NSString *)path callback:(RCTResponseSenderBlock) callback)
  285. {
  286. NSError * error = nil;
  287. NSString * tmpPath = nil;
  288. [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
  289. if(error == nil || [[NSFileManager defaultManager] fileExistsAtPath:path] == NO)
  290. callback(@[[NSNull null]]);
  291. else
  292. callback(@[[NSString stringWithFormat:@"failed to unlink file or path at %@", path]]);
  293. }
  294. #pragma mark - fs.removeSession
  295. RCT_EXPORT_METHOD(removeSession:(NSArray *)paths callback:(RCTResponseSenderBlock) callback)
  296. {
  297. NSError * error = nil;
  298. NSString * tmpPath = nil;
  299. for(NSString * path in paths) {
  300. [[NSFileManager defaultManager] removeItemAtPath:path error:&error];
  301. if(error != nil) {
  302. callback(@[[NSString stringWithFormat:@"failed to remove session path at %@", path]]);
  303. return;
  304. }
  305. }
  306. callback(@[[NSNull null]]);
  307. }
  308. #pragma mark - fs.ls
  309. RCT_EXPORT_METHOD(ls:(NSString *)path resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  310. {
  311. NSFileManager* fm = [NSFileManager defaultManager];
  312. BOOL exist = nil;
  313. BOOL isDir = nil;
  314. exist = [fm fileExistsAtPath:path isDirectory:&isDir];
  315. if(exist == NO) {
  316. return reject(@"ENOENT", [NSString stringWithFormat:@"No such file '%@'", path], nil);
  317. }
  318. if(isDir == NO) {
  319. return reject(@"ENOTDIR", [NSString stringWithFormat:@"Not a directory '%@'", path], nil);
  320. }
  321. NSError * error = nil;
  322. NSArray * result = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
  323. if(error == nil)
  324. resolve(result);
  325. else
  326. reject(@"EUNSPECIFIED", [error description], nil);
  327. }
  328. #pragma mark - fs.stat
  329. RCT_EXPORT_METHOD(stat:(NSString *)target callback:(RCTResponseSenderBlock) callback)
  330. {
  331. [RNFetchBlobFS getPathFromUri:target completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  332. __block NSMutableArray * result;
  333. if(path != nil)
  334. {
  335. NSFileManager* fm = [NSFileManager defaultManager];
  336. BOOL exist = nil;
  337. BOOL isDir = nil;
  338. NSError * error = nil;
  339. exist = [fm fileExistsAtPath:path isDirectory:&isDir];
  340. if(exist == NO) {
  341. callback(@[[NSString stringWithFormat:@"failed to stat path `%@` because it does not exist or it is not a folder", path]]);
  342. return ;
  343. }
  344. result = [RNFetchBlobFS stat:path error:&error];
  345. if(error == nil)
  346. callback(@[[NSNull null], result]);
  347. else
  348. callback(@[[error localizedDescription], [NSNull null]]);
  349. }
  350. else if(asset != nil)
  351. {
  352. __block NSNumber * size = [NSNumber numberWithLong:[asset size]];
  353. result = [asset metadata];
  354. [result setValue:size forKey:@"size"];
  355. callback(@[[NSNull null], result]);
  356. }
  357. else
  358. {
  359. callback(@[@"failed to stat path, could not resolve URI", [NSNull null]]);
  360. }
  361. }];
  362. }
  363. #pragma mark - fs.lstat
  364. RCT_EXPORT_METHOD(lstat:(NSString *)path callback:(RCTResponseSenderBlock) callback)
  365. {
  366. NSFileManager* fm = [NSFileManager defaultManager];
  367. BOOL exist = nil;
  368. BOOL isDir = nil;
  369. path = [RNFetchBlobFS getPathOfAsset:path];
  370. exist = [fm fileExistsAtPath:path isDirectory:&isDir];
  371. if(exist == NO) {
  372. callback(@[[NSString stringWithFormat:@"failed to lstat path `%@` because it does not exist or it is not a folder", path]]);
  373. return ;
  374. }
  375. NSError * error = nil;
  376. NSArray * files = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
  377. NSMutableArray * res = [[NSMutableArray alloc] init];
  378. if(isDir == YES) {
  379. for(NSString * p in files) {
  380. NSString * filePath = [NSString stringWithFormat:@"%@/%@", path, p];
  381. [res addObject:[RNFetchBlobFS stat:filePath error:&error]];
  382. }
  383. }
  384. else {
  385. [res addObject:[RNFetchBlobFS stat:path error:&error]];
  386. }
  387. if(error == nil)
  388. callback(@[[NSNull null], res == nil ? [NSNull null] :res ]);
  389. else
  390. callback(@[[error localizedDescription], [NSNull null]]);
  391. }
  392. #pragma mark - fs.cp
  393. RCT_EXPORT_METHOD(cp:(NSString*)src toPath:(NSString *)dest callback:(RCTResponseSenderBlock) callback)
  394. {
  395. // path = [RNFetchBlobFS getPathOfAsset:path];
  396. [RNFetchBlobFS getPathFromUri:src completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  397. NSError * error = nil;
  398. if(path == nil)
  399. {
  400. [RNFetchBlobFS writeAssetToPath:asset dest:dest];
  401. callback(@[[NSNull null], @YES]);
  402. }
  403. else
  404. {
  405. // If the destination exists there will be an error
  406. BOOL result = [[NSFileManager defaultManager] copyItemAtURL:[NSURL fileURLWithPath:path] toURL:[NSURL fileURLWithPath:dest] error:&error];
  407. if(error == nil)
  408. callback(@[[NSNull null], @YES]);
  409. else
  410. callback(@[[error localizedDescription], @NO]);
  411. }
  412. }];
  413. }
  414. #pragma mark - fs.mv
  415. RCT_EXPORT_METHOD(mv:(NSString *)path toPath:(NSString *)dest callback:(RCTResponseSenderBlock) callback)
  416. {
  417. NSError * error = nil;
  418. BOOL result = [[NSFileManager defaultManager] moveItemAtURL:[NSURL fileURLWithPath:path] toURL:[NSURL fileURLWithPath:dest] error:&error];
  419. if(error == nil)
  420. callback(@[[NSNull null], @YES]);
  421. else
  422. callback(@[[error localizedDescription], @NO]);
  423. }
  424. #pragma mark - fs.mkdir
  425. RCT_EXPORT_METHOD(mkdir:(NSString *)path resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  426. {
  427. [RNFetchBlobFS mkdir:path resolver:resolve rejecter:reject];
  428. }
  429. #pragma mark - fs.readFile
  430. RCT_EXPORT_METHOD(readFile:(NSString *)path
  431. encoding:(NSString *)encoding
  432. resolver:(RCTPromiseResolveBlock)resolve
  433. rejecter:(RCTPromiseRejectBlock)reject)
  434. {
  435. [RNFetchBlobFS readFile:path encoding:encoding onComplete:^(NSData * content, NSString * code, NSString * err) {
  436. if(err != nil) {
  437. reject(code, err, nil);
  438. return;
  439. }
  440. if(encoding == @"ascii") {
  441. resolve((NSMutableArray *)content);
  442. }
  443. else {
  444. resolve((NSString *)content);
  445. }
  446. }];
  447. }
  448. #pragma mark - fs.hash
  449. RCT_EXPORT_METHOD(hash:(NSString *)path
  450. algorithm:(NSString *)algorithm
  451. resolver:(RCTPromiseResolveBlock)resolve
  452. rejecter:(RCTPromiseRejectBlock)reject)
  453. {
  454. [RNFetchBlobFS hash:path algorithm:[NSString stringWithString:algorithm] resolver:resolve rejecter:reject];
  455. }
  456. #pragma mark - fs.readStream
  457. RCT_EXPORT_METHOD(readStream:(NSString *)path withEncoding:(NSString *)encoding bufferSize:(int)bufferSize tick:(int)tick streamId:(NSString *)streamId)
  458. {
  459. if(bufferSize == nil) {
  460. if([[encoding lowercaseString] isEqualToString:@"base64"])
  461. bufferSize = 4095;
  462. else
  463. bufferSize = 4096;
  464. }
  465. dispatch_async(fsQueue, ^{
  466. [RNFetchBlobFS readStream:path encoding:encoding bufferSize:bufferSize tick:tick streamId:streamId bridgeRef:_bridge];
  467. });
  468. }
  469. #pragma mark - fs.getEnvionmentDirs
  470. RCT_EXPORT_METHOD(getEnvironmentDirs:(RCTResponseSenderBlock) callback)
  471. {
  472. callback(@[
  473. [RNFetchBlobFS getDocumentDir],
  474. [RNFetchBlobFS getCacheDir],
  475. ]);
  476. }
  477. #pragma mark - net.cancelRequest
  478. RCT_EXPORT_METHOD(cancelRequest:(NSString *)taskId callback:(RCTResponseSenderBlock)callback) {
  479. [[RNFetchBlobNetwork sharedInstance] cancelRequest:taskId];
  480. callback(@[[NSNull null], taskId]);
  481. }
  482. #pragma mark - net.enableProgressReport
  483. RCT_EXPORT_METHOD(enableProgressReport:(NSString *)taskId interval:(nonnull NSNumber*)interval count:(nonnull NSNumber*)count)
  484. {
  485. RNFetchBlobProgress * cfg = [[RNFetchBlobProgress alloc] initWithType:Download interval:interval count:count];
  486. [[RNFetchBlobNetwork sharedInstance] enableProgressReport:taskId config:cfg];
  487. }
  488. #pragma mark - net.enableUploadProgressReport
  489. RCT_EXPORT_METHOD(enableUploadProgressReport:(NSString *)taskId interval:(nonnull NSNumber*)interval count:(nonnull NSNumber*)count)
  490. {
  491. RNFetchBlobProgress * cfg = [[RNFetchBlobProgress alloc] initWithType:Upload interval:interval count:count];
  492. [[RNFetchBlobNetwork sharedInstance] enableUploadProgress:taskId config:cfg];
  493. }
  494. #pragma mark - fs.slice
  495. RCT_EXPORT_METHOD(slice:(NSString *)src dest:(NSString *)dest start:(nonnull NSNumber *)start end:(nonnull NSNumber *)end resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  496. {
  497. [RNFetchBlobFS slice:src dest:dest start:start end:end encode:@"" resolver:resolve rejecter:reject];
  498. }
  499. RCT_EXPORT_METHOD(previewDocument:(NSString*)uri scheme:(NSString *)scheme resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  500. {
  501. NSString * utf8uri = [uri stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  502. NSURL * url = [[NSURL alloc] initWithString:utf8uri];
  503. // NSURL * url = [[NSURL alloc] initWithString:uri];
  504. documentController = [UIDocumentInteractionController interactionControllerWithURL:url];
  505. UIViewController *rootCtrl = [[[[UIApplication sharedApplication] delegate] window] rootViewController];
  506. documentController.delegate = self;
  507. if(scheme == nil || [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:scheme]]) {
  508. CGRect rect = CGRectMake(0.0, 0.0, 0.0, 0.0);
  509. dispatch_sync(dispatch_get_main_queue(), ^{
  510. [documentController presentOptionsMenuFromRect:rect inView:rootCtrl.view animated:YES];
  511. });
  512. resolve(@[[NSNull null]]);
  513. } else {
  514. reject(@"EINVAL", @"scheme is not supported", nil);
  515. }
  516. }
  517. # pragma mark - open file with UIDocumentInteractionController and delegate
  518. RCT_EXPORT_METHOD(openDocument:(NSString*)uri scheme:(NSString *)scheme resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  519. {
  520. NSString * utf8uri = [uri stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
  521. NSURL * url = [[NSURL alloc] initWithString:utf8uri];
  522. // NSURL * url = [[NSURL alloc] initWithString:uri];
  523. documentController = [UIDocumentInteractionController interactionControllerWithURL:url];
  524. documentController.delegate = self;
  525. if(scheme == nil || [[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:scheme]]) {
  526. dispatch_sync(dispatch_get_main_queue(), ^{
  527. if([documentController presentPreviewAnimated:YES]) {
  528. resolve(@[[NSNull null]]);
  529. } else {
  530. reject(@"EINVAL", @"document is not supported", nil);
  531. }
  532. });
  533. } else {
  534. reject(@"EINVAL", @"scheme is not supported", nil);
  535. }
  536. }
  537. # pragma mark - exclude from backup key
  538. RCT_EXPORT_METHOD(excludeFromBackupKey:(NSString *)url resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject)
  539. {
  540. NSError *error = nil;
  541. [ [NSURL URLWithString:url] setResourceValue:[NSNumber numberWithBool:YES] forKey:NSURLIsExcludedFromBackupKey error:&error];
  542. if(!error)
  543. {
  544. resolve(@[[NSNull null]]);
  545. } else {
  546. reject(@"EUNSPECIFIED", [error description], nil);
  547. }
  548. }
  549. RCT_EXPORT_METHOD(df:(RCTResponseSenderBlock)callback)
  550. {
  551. [RNFetchBlobFS df:callback];
  552. }
  553. - (UIViewController *) documentInteractionControllerViewControllerForPreview: (UIDocumentInteractionController *) controller
  554. {
  555. UIWindow *window = [UIApplication sharedApplication].keyWindow;
  556. return window.rootViewController;
  557. }
  558. # pragma mark - check expired network events
  559. RCT_EXPORT_METHOD(emitExpiredEvent:(RCTResponseSenderBlock)callback)
  560. {
  561. [RNFetchBlobNetwork emitExpiredTasks];
  562. }
  563. @end