React Native Expo için uygulama açılışında asset indirme sistemi yapmıştım kendim için daha önce.
Kod
import * as FileSystem from 'expo-file-system';
export class AssetsDownloader
{
/**
* expo construactor
* @param {*} u -> url
* @param {*} n -> name
*/
downloadResumable = (u, n) => {
return FileSystem.createDownloadResumable(
u,
this.dir + n,
{},
this.callback
);
}
/**
*
* @param {*} downloadProgress -> from downloadResumable
*/
callback = downloadProgress => {
const progress = downloadProgress.totalBytesWritten / downloadProgress.totalBytesExpectedToWrite;
return progress;
}
/**
*
* @param {*} fn -> Function that fetch the asset list
*/
constructor(fn) {
this.fn = fn;
this.assets = [];
this.dir = FileSystem.documentDirectory + "assets/";
}
/**
*
* @param {*} k -> Key name // ex: data.image (key: image)
* @param {*} b -> BASE_API_URL
*/
getFiles = async(k, b) => {
let res = await this.fn();
if (res.data?.length == 0 || res.data == undefined) this.assets = [];
const { data } = res;
data.forEach((item) => {
this.assets.push({
url: item[k] != null ? `${b}${item[k]}`: null,
name: item[k]
});
})
return this.assets;
}
downloadAssets = async(assets) => {
let dir = await FileSystem.getInfoAsync(this.dir);
if (!dir.exists) await FileSystem.makeDirectoryAsync(this.dir, { intermediates: true });
assets.forEach(async(item) => {
var info = await FileSystem.getInfoAsync(this.dir + item.name)
if (info.exists) return console.log(`Assets ${item.name} already downloaded!`)
this.downloadResumable(item.url, item.name).downloadAsync().then(({ uri }) => {
console.log(`Assets ${item.name} downloaded!`)
})
})
}
}
Kullanımı:
Kod
let url = "https://blabla.com/api/getImages/";
const getImages = async() => {
let res = await axios.get(url);
}
const assetDownloader = new AssetsDownloader(getImages);
assetDownloader.getFiles("name", url).then((res) => {
var filteredAssets = res.filter(x => x.name != null);
assetDownloader.downloadAssets(filteredAssets);
})