I'm in the process of building an iOS application that will, when prompted by the user, fetch a large JSON file containing image URLs.
How can I download these images so that they will be available for use by my application even when it has no access to wifi/data?
To download an image using rn-fetch-blob we will use the RNFetchBlob component which provides a fetch method with some different configuration. Here is the code snippet to download the image.
To have offline-first functionality when the app is launched and there is no connection, you will need to add redux-persist to your app. This enables it to store a snapshot of the state of your app to the device's memory and rehydrate the state when the app is launched.
Any images that you import in your React components should be stored close to where they are used (preferably in the same directory). Any images that you do not import in your React components (e.g. favicons ) should be stored in your public/ directory, e.g. under a favicons/ folder.
To make our app work offline, we need to get the web assets to work offline. Create React App already has the required boilerplate for making an app offline using service workers. Open src/index. js and change the line that says serviceWorker.
React Native has poor support to binary data, you are not be able to get the binary data directly via fetch
. However you can use XMLHttpRequest in 0.30 branch or CameraRoll
, refer to this post.
If you want to persist those image data, consider use AsyncStorage.
There're also several open source modules help you deal with file access if you want to store the images in file system.
react-native-fs
react-native-fetch-blob
NOTE: react-native-fetch-blob has been discontinued. rn-fetch-blob is a fork of it that is still maintained. When using npm, don't include react-native-fetch-blob but rn-fetch-blob instead.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With