Ingen beskrivning

RNFetchBlobFS.m 22KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621
  1. //
  2. // RNFetchBlobFS.m
  3. // RNFetchBlob
  4. //
  5. // Created by Ben Hsieh on 2016/6/6.
  6. // Copyright © 2016年 suzuri04x2. All rights reserved.
  7. //
  8. #import "RCTConvert.h"
  9. #import "RCTLog.h"
  10. #import <Foundation/Foundation.h>
  11. #import "RCTBridge.h"
  12. #import "RCTEventDispatcher.h"
  13. #import "RNFetchBlobFS.h"
  14. #import "RNFetchBlobConst.h"
  15. @import AssetsLibrary;
  16. NSMutableDictionary *fileStreams = nil;
  17. ////////////////////////////////////////
  18. //
  19. // File system access methods
  20. //
  21. ////////////////////////////////////////
  22. @implementation RNFetchBlobFS
  23. @synthesize outStream;
  24. @synthesize inStream;
  25. @synthesize encoding;
  26. @synthesize callback;
  27. @synthesize taskId;
  28. @synthesize path;
  29. @synthesize appendData;
  30. @synthesize bufferSize;
  31. // static member getter
  32. + (NSArray *) getFileStreams {
  33. if(fileStreams == nil)
  34. fileStreams = [[NSMutableDictionary alloc] init];
  35. return fileStreams;
  36. }
  37. +(void) setFileStream:(RNFetchBlobFS *) instance withId:(NSString *) uuid {
  38. if(fileStreams == nil)
  39. fileStreams = [[NSMutableDictionary alloc] init];
  40. [fileStreams setValue:instance forKey:uuid];
  41. }
  42. +(NSString *) getPathOfAsset:(NSString *)assetURI
  43. {
  44. // get file path of an app asset
  45. if([assetURI hasPrefix:ASSET_PREFIX])
  46. {
  47. assetURI = [assetURI stringByReplacingOccurrencesOfString:ASSET_PREFIX withString:@""];
  48. assetURI = [[NSBundle mainBundle] pathForResource: [assetURI stringByDeletingPathExtension]
  49. ofType: [assetURI pathExtension]];
  50. }
  51. return assetURI;
  52. }
  53. + (NSString *) getCacheDir {
  54. return [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) firstObject];
  55. }
  56. + (NSString *) getDocumentDir {
  57. return [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  58. }
  59. + (NSString *) getMusicDir {
  60. return [NSSearchPathForDirectoriesInDomains(NSMusicDirectory, NSUserDomainMask, YES) firstObject];
  61. }
  62. + (NSString *) getMovieDir {
  63. return [NSSearchPathForDirectoriesInDomains(NSMoviesDirectory, NSUserDomainMask, YES) firstObject];
  64. }
  65. + (NSString *) getPictureDir {
  66. return [NSSearchPathForDirectoriesInDomains(NSPicturesDirectory, NSUserDomainMask, YES) firstObject];
  67. }
  68. + (NSString *) getTempPath {
  69. return [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject] stringByAppendingString:@"/RNFetchBlob_tmp"];
  70. }
  71. + (NSString *) getTempPath:(NSString*)taskId withExtension:(NSString *)ext {
  72. NSString * documentDir = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) firstObject];
  73. NSString * filename = [NSString stringWithFormat:@"/RNFetchBlob_tmp/RNFetchBlobTmp_%@", taskId];
  74. if(ext != nil)
  75. filename = [filename stringByAppendingString: [NSString stringWithFormat:@".%@", ext]];
  76. NSString * tempPath = [documentDir stringByAppendingString: filename];
  77. return tempPath;
  78. }
  79. - (void) startAssetReadStream:(NSString *)assetUrl
  80. {
  81. ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *myasset)
  82. {
  83. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
  84. dispatch_async(queue, ^ {
  85. NSString * streamEventCode = [NSString stringWithFormat:@"RNFetchBlobStream+%@", self.path];
  86. ALAssetRepresentation *rep = [myasset defaultRepresentation];
  87. Byte *buffer = (Byte*)malloc(self.bufferSize);
  88. NSUInteger cursor = [rep getBytes:buffer fromOffset:0 length:self.bufferSize error:nil];
  89. while(cursor > 0)
  90. {
  91. cursor += [rep getBytes:buffer fromOffset:cursor length:self.bufferSize error:nil];
  92. NSData * chunkData = [NSData dataWithBytes:buffer length:self.bufferSize];
  93. NSString * encodedChunk = @"";
  94. // emit data
  95. if( [[self.encoding lowercaseString] isEqualToString:@"utf8"] ) {
  96. encodedChunk = [encodedChunk initWithData:chunkData encoding:NSUTF8StringEncoding];
  97. }
  98. // when encoding is ASCII, send byte array data
  99. else if ( [[self.encoding lowercaseString] isEqualToString:@"ascii"] ) {
  100. // RCTBridge only emits string data, so we have to create JSON byte array string
  101. NSMutableArray * asciiArray = [NSMutableArray array];
  102. unsigned char *bytePtr;
  103. if (chunkData.length > 0)
  104. {
  105. bytePtr = (unsigned char *)[chunkData bytes];
  106. NSInteger byteLen = chunkData.length/sizeof(uint8_t);
  107. for (int i = 0; i < byteLen; i++)
  108. {
  109. [asciiArray addObject:[NSNumber numberWithChar:bytePtr[i]]];
  110. }
  111. }
  112. [self.bridge.eventDispatcher
  113. sendDeviceEventWithName:streamEventCode
  114. body: @{
  115. @"event": FS_EVENT_DATA,
  116. @"detail": asciiArray
  117. }
  118. ];
  119. return;
  120. }
  121. // convert byte array to base64 data chunks
  122. else if ( [[self.encoding lowercaseString] isEqualToString:@"base64"] ) {
  123. encodedChunk = [chunkData base64EncodedStringWithOptions:0];
  124. }
  125. // unknown encoding, send error event
  126. else {
  127. [self.bridge.eventDispatcher
  128. sendDeviceEventWithName:streamEventCode
  129. body:@{
  130. @"event": FS_EVENT_ERROR,
  131. @"detail": @"unrecognized encoding"
  132. }
  133. ];
  134. return;
  135. }
  136. [self.bridge.eventDispatcher
  137. sendDeviceEventWithName:streamEventCode
  138. body:@{
  139. @"event": FS_EVENT_DATA,
  140. @"detail": encodedChunk
  141. }
  142. ];
  143. }
  144. free(buffer);
  145. });
  146. };
  147. ALAssetsLibraryAccessFailureBlock failureblock = ^(NSError *error)
  148. {
  149. };
  150. if(assetUrl && [assetUrl length])
  151. {
  152. NSURL *asseturl = [NSURL URLWithString:assetUrl];
  153. ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
  154. [assetslibrary assetForURL:asseturl
  155. resultBlock:resultblock
  156. failureBlock:failureblock];
  157. }
  158. }
  159. + (void) writeFile:(NSString *)path encoding:(NSString *)encoding data:(NSString *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
  160. @try {
  161. NSFileManager * fm = [NSFileManager defaultManager];
  162. NSError * err = nil;
  163. // check if the folder exists, if not exists, create folders recursively
  164. // after the folders created, write data into the file
  165. NSString * folder = [path stringByDeletingLastPathComponent];
  166. if(![fm fileExistsAtPath:folder]) {
  167. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:&err];
  168. }
  169. // if file exists, write file by encoding and strategy
  170. if(![fm fileExistsAtPath:path]) {
  171. if([[encoding lowercaseString] isEqualToString:@"base64"]){
  172. NSData * byteData = [[NSData alloc] initWithBase64EncodedString:data options:0];
  173. [fm createFileAtPath:path contents:byteData attributes:NULL];
  174. }
  175. else
  176. [fm createFileAtPath:path contents:[data dataUsingEncoding:NSUTF8StringEncoding] attributes:NULL];
  177. }
  178. else {
  179. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
  180. NSData * content = nil;
  181. if([[encoding lowercaseString] isEqualToString:@"base64"]) {
  182. content = [[NSData alloc] initWithBase64EncodedString:data options:0];
  183. }
  184. else {
  185. content = [data dataUsingEncoding:NSUTF8StringEncoding];
  186. }
  187. if(append == YES) {
  188. [fileHandle seekToEndOfFile];
  189. [fileHandle writeData:content];
  190. [fileHandle closeFile];
  191. }
  192. else {
  193. [content writeToFile:path atomically:YES];
  194. }
  195. }
  196. fm = nil;
  197. resolve([NSNull null]);
  198. }
  199. @catch (NSException * e)
  200. {
  201. reject(@"RNFetchBlob writeFile Error", @"Error", [e description]);
  202. }
  203. }
  204. + (void) writeFileArray:(NSString *)path data:(NSArray *)data append:(BOOL)append resolver:(RCTPromiseResolveBlock)resolve rejecter:(RCTPromiseRejectBlock)reject {
  205. @try {
  206. NSFileManager * fm = [NSFileManager defaultManager];
  207. NSError * err = nil;
  208. // check if the folder exists, if not exists, create folders recursively
  209. // after the folders created, write data into the file
  210. NSString * folder = [path stringByDeletingLastPathComponent];
  211. if(![fm fileExistsAtPath:folder]) {
  212. [fm createDirectoryAtPath:folder withIntermediateDirectories:YES attributes:NULL error:&err];
  213. }
  214. NSMutableData * fileContent = [NSMutableData alloc];
  215. // prevent stack overflow, alloc on heap
  216. char * bytes = (char*) malloc([data count]);
  217. for(int i = 0; i < data.count; i++) {
  218. bytes[i] = [[data objectAtIndex:i] charValue];
  219. }
  220. [fileContent appendBytes:bytes length:data.count];
  221. if(![fm fileExistsAtPath:path]) {
  222. [fm createFileAtPath:path contents:fileContent attributes:NULL];
  223. }
  224. // if file exists, write file
  225. else {
  226. if(append == YES) {
  227. NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:path];
  228. [fileHandle seekToEndOfFile];
  229. [fileHandle writeData:fileContent];
  230. [fileHandle closeFile];
  231. }
  232. else {
  233. [fileContent writeToFile:path atomically:YES];
  234. }
  235. }
  236. free(bytes);
  237. fm = nil;
  238. resolve([NSNull null]);
  239. }
  240. @catch (NSException * e)
  241. {
  242. reject(@"RNFetchBlob writeFile Error", @"Error", [e description]);
  243. }
  244. }
  245. + (void) readFile:(NSString *)path encoding:(NSString *)encoding
  246. resolver:(RCTPromiseResolveBlock)resolve
  247. rejecter:(RCTPromiseRejectBlock)reject
  248. onComplete:(void (^)(NSData * content))onComplete
  249. {
  250. @try
  251. {
  252. [[self class] getPathFromUri:path completionHandler:^(NSString *path, ALAssetRepresentation *asset) {
  253. NSData * fileContent;
  254. NSError * err;
  255. if(asset != nil)
  256. {
  257. Byte * buffer = malloc(asset.size);
  258. [asset getBytes:buffer fromOffset:0 length:asset.size error:&err];
  259. if(err != nil)
  260. {
  261. reject(@"RNFetchBlobFS readFile error", @"failed to read asset", [err localizedDescription]);
  262. return;
  263. }
  264. fileContent = [NSData dataWithBytes:buffer length:asset.size];
  265. if(onComplete != nil)
  266. onComplete(fileContent);
  267. free(buffer);
  268. }
  269. else
  270. {
  271. BOOL exists = [[NSFileManager defaultManager] fileExistsAtPath:path];
  272. if(!exists) {
  273. reject(@"RNFetchBlobFS readFile error", @"file not exists", path);
  274. return;
  275. }
  276. fileContent = [NSData dataWithContentsOfFile:path];
  277. }
  278. if([[encoding lowercaseString] isEqualToString:@"utf8"]) {
  279. if(resolve != nil)
  280. resolve([[NSString alloc] initWithData:fileContent encoding:NSUTF8StringEncoding]);
  281. }
  282. else if ([[encoding lowercaseString] isEqualToString:@"base64"]) {
  283. if(resolve != nil)
  284. resolve([fileContent base64EncodedStringWithOptions:0]);
  285. }
  286. else if ([[encoding lowercaseString] isEqualToString:@"ascii"]) {
  287. NSMutableArray * resultArray = [NSMutableArray array];
  288. char * bytes = [fileContent bytes];
  289. for(int i=0;i<[fileContent length];i++) {
  290. [resultArray addObject:[NSNumber numberWithChar:bytes[i]]];
  291. }
  292. if(resolve != nil)
  293. resolve(resultArray);
  294. }
  295. }];
  296. }
  297. @catch(NSException * e)
  298. {
  299. if(reject != nil)
  300. reject(@"RNFetchBlobFS readFile error", @"error", [e description]);
  301. }
  302. }
  303. + (BOOL) mkdir:(NSString *) path {
  304. BOOL isDir;
  305. NSError * err = nil;
  306. // if temp folder not exists, create one
  307. if(![[NSFileManager defaultManager] fileExistsAtPath: path isDirectory:&isDir]) {
  308. [[NSFileManager defaultManager] createDirectoryAtPath:path withIntermediateDirectories:YES attributes:nil error:&err];
  309. }
  310. return err == nil;
  311. }
  312. + (NSDictionary *) stat:(NSString *) path error:(NSError **) error {
  313. NSMutableDictionary *stat = [[NSMutableDictionary alloc] init];
  314. BOOL isDir = NO;
  315. NSFileManager * fm = [NSFileManager defaultManager];
  316. if([fm fileExistsAtPath:path isDirectory:&isDir] == NO) {
  317. return nil;
  318. }
  319. NSDictionary * info = [fm attributesOfItemAtPath:path error:&error];
  320. NSString * size = [NSString stringWithFormat:@"%d", [info fileSize]];
  321. NSString * filename = [path lastPathComponent];
  322. NSDate * lastModified;
  323. [[NSURL fileURLWithPath:path] getResourceValue:&lastModified forKey:NSURLContentModificationDateKey error:&error];
  324. return @{
  325. @"size" : size,
  326. @"filename" : filename,
  327. @"path" : path,
  328. @"lastModified" : [NSString stringWithFormat:@"%d", [lastModified timeIntervalSince1970]],
  329. @"type" : isDir ? @"directory" : @"file"
  330. };
  331. }
  332. + (BOOL) exists:(NSString *) path {
  333. return [[NSFileManager defaultManager] fileExistsAtPath:path isDirectory:NULL];
  334. }
  335. - (id)init {
  336. self = [super init];
  337. return self;
  338. }
  339. - (id)initWithCallback:(RCTResponseSenderBlock)callback {
  340. self = [super init];
  341. self.callback = callback;
  342. return self;
  343. }
  344. - (id)initWithBridgeRef:(RCTBridge *)bridgeRef {
  345. self = [super init];
  346. self.bridge = bridgeRef;
  347. return self;
  348. }
  349. // Create file stream for write data
  350. - (NSString *)openWithPath:(NSString *)destPath encode:(nullable NSString *)encode appendData:(BOOL)append {
  351. self.outStream = [[NSOutputStream alloc] initToFileAtPath:destPath append:append];
  352. self.encoding = encode;
  353. [self.outStream scheduleInRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  354. [self.outStream open];
  355. NSString *uuid = [[NSUUID UUID] UUIDString];
  356. self.streamId = uuid;
  357. [RNFetchBlobFS setFileStream:self withId:uuid];
  358. return uuid;
  359. }
  360. // Write file chunk into an opened stream
  361. - (void)writeEncodeChunk:(NSString *) chunk {
  362. NSMutableData * decodedData = [NSData alloc];
  363. if([[self.encoding lowercaseString] isEqualToString:@"base64"]) {
  364. decodedData = [[NSData alloc] initWithBase64EncodedData:chunk options:0];
  365. }
  366. if([[self.encoding lowercaseString] isEqualToString:@"utf8"]) {
  367. decodedData = [chunk dataUsingEncoding:NSUTF8StringEncoding];
  368. }
  369. else if([[self.encoding lowercaseString] isEqualToString:@"ascii"]) {
  370. decodedData = [chunk dataUsingEncoding:NSASCIIStringEncoding];
  371. }
  372. NSUInteger left = [decodedData length];
  373. NSUInteger nwr = 0;
  374. do {
  375. nwr = [self.outStream write:[decodedData bytes] maxLength:left];
  376. if (-1 == nwr) break;
  377. left -= nwr;
  378. } while (left > 0);
  379. if (left) {
  380. NSLog(@"stream error: %@", [self.outStream streamError]);
  381. }
  382. }
  383. // Write file chunk into an opened stream
  384. - (void)write:(NSData *) chunk {
  385. NSUInteger left = [chunk length];
  386. NSUInteger nwr = 0;
  387. do {
  388. nwr = [self.outStream write:[chunk bytes] maxLength:left];
  389. if (-1 == nwr) break;
  390. left -= nwr;
  391. } while (left > 0);
  392. if (left) {
  393. NSLog(@"stream error: %@", [self.outStream streamError]);
  394. }
  395. }
  396. // close file write stream
  397. - (void)closeOutStream {
  398. if(self.outStream != nil) {
  399. [self.outStream close];
  400. self.outStream = nil;
  401. }
  402. }
  403. - (void)readWithPath:(NSString *)path useEncoding:(NSString *)encoding bufferSize:(int) bufferSize {
  404. self.inStream = [[NSInputStream alloc] initWithFileAtPath:path];
  405. self.inStream.delegate = self;
  406. self.encoding = encoding;
  407. self.path = path;
  408. self.bufferSize = bufferSize;
  409. if([path hasPrefix:AL_PREFIX])
  410. {
  411. [self startAssetReadStream:path];
  412. return;
  413. }
  414. // normalize file path
  415. path = [[self class] getPathOfAsset:path];
  416. // NSStream needs a runloop so let's create a run loop for it
  417. dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);
  418. // start NSStream is a runloop
  419. dispatch_async(queue, ^ {
  420. [inStream scheduleInRunLoop:[NSRunLoop currentRunLoop]
  421. forMode:NSDefaultRunLoopMode];
  422. [inStream open];
  423. [[NSRunLoop currentRunLoop] run];
  424. });
  425. }
  426. // close file read stream
  427. - (void)closeInStream {
  428. if(self.inStream != nil) {
  429. [self.inStream close];
  430. [self.inStream removeFromRunLoop:[NSRunLoop currentRunLoop] forMode:NSRunLoopCommonModes];
  431. [[RNFetchBlobFS getFileStreams] setValue:nil forKey:self.streamId];
  432. self.streamId = nil;
  433. }
  434. }
  435. #pragma mark RNFetchBlobFS read stream delegate
  436. - (void)stream:(NSStream *)stream handleEvent:(NSStreamEvent)eventCode {
  437. NSString * streamEventCode = [NSString stringWithFormat:@"RNFetchBlobStream+%@", self.path];
  438. switch(eventCode) {
  439. // write stream event
  440. case NSStreamEventHasSpaceAvailable:
  441. {
  442. }
  443. // read stream incoming chunk
  444. case NSStreamEventHasBytesAvailable:
  445. {
  446. NSMutableData * chunkData = [[NSMutableData alloc] init];
  447. NSInteger chunkSize = 4096;
  448. if([[self.encoding lowercaseString] isEqualToString:@"base64"])
  449. chunkSize = 4095;
  450. if(self.bufferSize > 0)
  451. chunkSize = self.bufferSize;
  452. uint8_t buf[chunkSize];
  453. unsigned int len = 0;
  454. len = [(NSInputStream *)stream read:buf maxLength:chunkSize];
  455. // still have data in stream
  456. if(len) {
  457. [chunkData appendBytes:buf length:len];
  458. // dispatch data event
  459. NSString * encodedChunk = [NSString alloc];
  460. if( [[self.encoding lowercaseString] isEqualToString:@"utf8"] ) {
  461. encodedChunk = [encodedChunk initWithData:chunkData encoding:NSUTF8StringEncoding];
  462. }
  463. // when encoding is ASCII, send byte array data
  464. else if ( [[self.encoding lowercaseString] isEqualToString:@"ascii"] ) {
  465. // RCTBridge only emits string data, so we have to create JSON byte array string
  466. NSMutableArray * asciiArray = [NSMutableArray array];
  467. unsigned char *bytePtr;
  468. if (chunkData.length > 0)
  469. {
  470. bytePtr = (unsigned char *)[chunkData bytes];
  471. NSInteger byteLen = chunkData.length/sizeof(uint8_t);
  472. for (int i = 0; i < byteLen; i++)
  473. {
  474. [asciiArray addObject:[NSNumber numberWithChar:bytePtr[i]]];
  475. }
  476. }
  477. [self.bridge.eventDispatcher
  478. sendDeviceEventWithName:streamEventCode
  479. body: @{
  480. @"event": FS_EVENT_DATA,
  481. @"detail": asciiArray
  482. }
  483. ];
  484. return;
  485. }
  486. // convert byte array to base64 data chunks
  487. else if ( [[self.encoding lowercaseString] isEqualToString:@"base64"] ) {
  488. encodedChunk = [chunkData base64EncodedStringWithOptions:0];
  489. }
  490. // unknown encoding, send error event
  491. else {
  492. [self.bridge.eventDispatcher
  493. sendDeviceEventWithName:streamEventCode
  494. body:@{
  495. @"event": FS_EVENT_ERROR,
  496. @"detail": @"unrecognized encoding"
  497. }
  498. ];
  499. return;
  500. }
  501. [self.bridge.eventDispatcher
  502. sendDeviceEventWithName:streamEventCode
  503. body:@{
  504. @"event": FS_EVENT_DATA,
  505. @"detail": encodedChunk
  506. }
  507. ];
  508. }
  509. // end of stream
  510. else {
  511. [self.bridge.eventDispatcher
  512. sendDeviceEventWithName:streamEventCode
  513. body:@{
  514. @"event": FS_EVENT_END,
  515. @"detail": @""
  516. }
  517. ];
  518. }
  519. break;
  520. }
  521. // stream error
  522. case NSStreamEventErrorOccurred:
  523. {
  524. [self.bridge.eventDispatcher
  525. sendDeviceEventWithName:streamEventCode
  526. body:@{
  527. @"event": FS_EVENT_ERROR,
  528. @"detail": @"RNFetchBlob error when read file with stream, file may not exists"
  529. }
  530. ];
  531. break;
  532. }
  533. }
  534. }
  535. + (void) getPathFromUri:(NSString *)uri completionHandler:(void(^)(NSString * path, ALAssetRepresentation *asset)) onComplete
  536. {
  537. if([uri hasPrefix:AL_PREFIX])
  538. {
  539. NSURL *asseturl = [NSURL URLWithString:uri];
  540. ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
  541. [assetslibrary assetForURL:asseturl
  542. resultBlock:^(ALAsset *asset) {
  543. onComplete(nil, [asset defaultRepresentation]);
  544. }
  545. failureBlock:^(NSError *error) {
  546. onComplete(nil, nil);
  547. }];
  548. }
  549. else
  550. {
  551. onComplete([[self class] getPathOfAsset:uri], nil);
  552. }
  553. }
  554. @end