React Native RNFS delete file from download directory - react-native

I'm trying to delete some files from the Android Download Directory.
I got the android permission to the external storage to do it, so this is my code :
var RNFS = require('react-native-fs');
...
await RNFS.exists(filepath).then((exists) => {
if (exists) {
RNFS.unlink(filepath).then(() => {
RNFS.scanFile(filepath);
})
}
});
The unlink function works perfectly when I add some log in it. It doesn't catch(), but when I launch the same script again, the unlink still works while the file must be deleted, how is it possible ??
I don't understand what I have to do to completely delete these files...
EDIT :
I've checked the react-native-fs and it says :
Android support is currently limited to only the DocumentDirectory. This maps to the app's files directory.
So how can I delete files in the Download directory ?

Related

how to add asset files to a React Native iOS project

I am currently working on getting a react-native project that is running on Android to work on iOS. The following code uses react-native-blob-util to load files from the following folder android/app/src/main/assets/. So if the function is called with path "/app.js" it will read the file at android/app/src/main/assets/webview/app.js
async function buildLocalAssetResponse(path: string): Promise<Buffer> {
let headers = 'HTTP/1.1 ';
const bundlePath = `webview${path}`;
let data = '';
console.log(bundlePath)
try {
data = await ReactNativeBlobUtil.fs.readFile(
ReactNativeBlobUtil.fs.asset(bundlePath),
'base64',
);
I am trying to figure out how to get this working on iOS exactly, I believe I have to copy the relevant files into an ios assets folder so ReactNativeBlobUtil.fs.asset can find them but I am not sure how to create that folder.

How to download assets/files(.JSON) and store them inside my app not directly on the user's phone in React Native Expo

am using React Native Expo and I was browsing the web to find a way to download assets, and files to my react native project and came across with this post How to Download image in react native
When the user clicks the download button I want assets/files to be downloaded and stored inside the app not directly on the user's phone. I mean I don't want the users to view the downloaded files or delete them manually.
I just want the downloaded assets/files to be accessible by the React Native app. Am doing this to make the app work offline.
Once the users downloaded the assets/files, the app can use the downloaded assets/files. How can I accomplish that?
Thank you in advance!
If you are using expo managed workflow, then rn-fetch-blob will not work for you.
In that case, Expo File System is probably your way to go.
Firstly, install expo-file-system. See this
Next, for saving files and not letting users delete them manually, store them inside the cache-directory like this
import * as FileSystem from 'expo-file-system';
const downloadAssets = async () => {
let name = "Samplefile.jpg";
const result = FileSystem.createDownloadResumable(
url_Of_the_File_You_Want_to_Download,
FileSystem.cacheDirectory + name
);
const response = await result.downloadAsync();
if (response.status === 200) {
// File successfully saved
} else {
// Some error
}
};
To access this file in your app simple execute this function
import * as FileSystem from 'expo-file-system';
const getFiles = async () => {
const CacheDir = await FileSystem.readDirectoryAsync(
FileSystem.cacheDirectory
);
console.log(CacheDir); //Files are stored here
};

TypeError:null is not an object(evaluating 'RNFSManager.RNFSFileTypeRegular')

I am currently working on reading a local file in react-native and am running into the following error,
TypeError:null is not an object(evaluating 'RNFSManager.RNFSFileTypeRegular')
The code I am using is taken straight off of the documentation for react-native-fs , using the basic example, from the examples section:
// require the module
var RNFS = require('react-native-fs');
// get a list of files and directories in the main bundle
RNFS.readDir(RNFS.MainBundlePath) // On Android, use "RNFS.DocumentDirectoryPath" (MainBundlePath is not defined)
.then((result) => {
console.log('GOT RESULT', result);
// stat the first file
return Promise.all([RNFS.stat(result[0].path), result[0].path]);
})
.then((statResult) => {
if (statResult[0].isFile()) {
// if we have a file, read it
return RNFS.readFile(statResult[1], 'utf8');
}
return 'no file';
})
.then((contents) => {
// log the file contents
console.log(contents);
})
.catch((err) => {
console.log(err.message, err.code);
});
If it helps I am using vs when writing this on a Windows 10 computer.
I have tried resetting my cache, reinstalling react-native-fs, and linking react-native-fs, none have solved the problem all resulting in the same error.
I would greatly appreciate any help. Thank you.
In case of iOS message is 'Native module cannot be null', In Android message is 'null is not an object evaluating RNFSManager etc'
Solution for iOS is run pod install in iOS Directory, then react-native run-ios to re-run the app.
Solution for android is react-native link react-native-fs then react-native run-android to re-run the app.

React native fs iOS not showing files in the document directory

I am working on a react native project. I need to store the captured images in the custom folder.
I am using react native fs library for that. I am able to create the image in the desired directory but I am not able to see those images in my iphones' file directory.
Here is my code I am using to store the images.
async moveAttachment(capturedImagePath) {
$filePathDir = `${RNFS.DocumentDirectoryPath}/myapp/myfilename`;
$filePath = `${$filePathDir }/myfilename.png`;
return new Promise((resolve, reject) => {
RNFS.mkdir(filePathDir)
.then(() => {
RNFS.moveFile(capturedImagePath, filePath )
.then(() => resolve(dirPictures))
.catch(error => reject(error));
})
.catch(err => reject(err));
});
}
I am able to see the image in my simulator's document directory but not able to see in the iPhone > files directory.
Please help me to figure this out.
You should be able to enable it by updating your Info.plist. You need to add two keys:
UIFileSharingEnabled and LSSupportsOpeningDocumentsInPlace should both be added and set to YES.
UIFileSharingEnabled: Application supports iTunes file sharing
LSSupportsOpeningDocumentsInPlace: Supports opening documents in place
This will allow your DocumentsDirectory to be opened in iTunes and it should also allow you to share your files via the Files application.
You can read more about LSSupportsOpeningDocumentsInPlace here
In iOS 11 and later, if both this key and the UIFileSharingEnabled key
are YES, the local file provider grants access to all the documents in
the app’s Documents directory. These documents appear in the Files
app, and in a document browser. Users can open and edit these document
in place.
Note that any item you save in the Documents directory will be accessible.

How do you require() a sound file in React Native?

I'm using https://github.com/zmxv/react-native-sound to play sounds on my iOS (and Android) app, and I'm trying to include sound files through React Native's asset system, but when I call:
var sound = require('./sound.mp3');
I get the error:
Unable to resolve module ./sound.mp3 from [project]/index.ios.js: Invalid directory [project]/sound.mp3
I have my MP3 file in the correct (root) directory of my project, the exact same file path that the error is printing. I've tried putting it in other directories as well.
According to this thread, it sounds like sound files should be able to be packaged using require() as well?
Just doing a test, requiring an image works perfectly:
var image = require('./image.png');
What worked for me was simply using the app name as root:
import myMP3File from '<appname>/assets/mymp3.mp3';
const Sound = require('react-native-sound');
Sound.setCategory('Playback');
// Do whatever you like with it.
Sound(myMP3File, () => console.log('soundfile loaded!'));
Edit:
We now use rn-fetch-blob and the following solution to access local files:
import RNFetchBlob from 'rn-fetch-blob';
const { fs } = RNFetchBlob;
filePathIos = `${fs.dirs.MainBundleDir}/yourFolder/yourMp3.mp3`;
filePathAndroid = fs.asset('yourFolder/yourMp3.mp3');
The corresponding path can then be used to copy the file using fs.cp().
The only thing that worked for us is to put the audio files we want to ship with the app in an assets directory and then have Xcode copy those files into the app bundle at build time. At that point, you can calculate the full path to the file using something like react-native-fs, and provide that to react-native-sound.
I had the same error message with managed Expo when trying to play a sound.ogg.
None of the trick I could find worked.
In the end, what solved it was to convert the ogg file to mp3, which is supported by Expo.
You need to use react-native-asset to put files to your project and access them with require keyword.
Example for file with path ./assets/audio/some-audio.mp3:
Add or modify react-native.config.js
module.exports = {
project: {
ios: {},
android: {},
},
dependencies: {
},
assets: [
'./assets/audio'
],
};
Run npx react-native-asset
Use the file:
const someAudio = require('./assets/audio/some-audio.mp3')