我正在使用 react-native-fetch-blob 下载 mp3 文件,稍后再播放。问题是 RNFetchBlob.fs.dirs.DocumentDir
的实际路径在我关闭应用程序并再次重新启动时发生了变化,这意味着我无法使用下载文件后立即存储的绝对文件路径在下次运行应用程序时检索文件。
这是我下载和存储文件路径的代码:
export function downloadAudio(urlArray) { //download every section in the urlArray
return (dispatch) => {
Promise.all(urlArray.map(section => {
dispatch(startDownload(section.section_id))
console.log('download start for id = ',section.section_id ) //start download
return RNFetchBlob
.config({
path: RNFetchBlob.fs.dirs.DocumentDir + '/courseSections/' + section.section_id + '.mp3',
appendExt: 'mp3'
})
.fetch('GET', section.section_url, {
'Cache-Control': 'no-store'
})
.progress({ count: 10 }, (received, total) => {
console.log(`progress for section ${section.section_id}: `, Math.floor(received/total*100), '%')
dispatch(downloadProgress({id: section.section_id, progress: Math.floor(received/total*100)/100}))
})
.then(res => {
console.log(`section ${section.section_id} is saved to: `, res.path())
return { path: res.path(), id: section.section_id }
})
.then(pathInfo => dispatch(downloadSuccess(pathInfo))) //download finished
}))
.catch((error, statusCode) => {
console.log(statusCode, ' error: ', error)
})
}
}
我将 { path: res.path(), id: section.section_id }
存储为持久化应用程序状态的一部分。但这没有用,因为下次我打开应用程序时,文件路径已被重新分配。例如,这是一个文件下载到的路径:
downloaded file path
但是在我关闭应用程序并重新启动后,路径更改为:
/Users/NatashaChe/Library/Developer/CoreSimulator/Devices/830778DE-3CE3-4FC7-AA4B-DFBAE999751C/data/Containers/Data/Application/0C47E33F-ACF8-4539-9456-8FF3E8FBECB2/Documents/courseSections/14。 mp3
即这些文件被分配到 Application
文件夹下的不同子文件夹。
显然,音频播放器(我使用的是 react-native-sound)无法使用应用程序存储的原始路径找到文件。所以我的问题是:有没有办法修复路径?还是有其他一些我不知道的检索文件的方法?
此外,我还在我的电脑上使用 iOS 模拟器。还没有在电话上试过这个。有谁知道上面的代码是否可以直接在iphone上使用并将文件保存到我的应用程序目录中?或者我应该以任何其他方式设置文件路径吗?
我使用的是 React Native 0.41。
最佳答案
我做了以下更改以使其工作,至少目前在模拟器上是这样。不确定实际手机上会发生什么。
在检索文件时,我现在直接使用filePath = RNFetchBlob.fs.dirs,而不是像上面的代码那样使用
检索文件时。 res.path()
返回的文件路径。 DocumentDir + '/courseSections/' + sectionInfo.section.section_id + '.mp3'
关于ios - 如何使用 react native 和 react-native-fetch-blob 在 iOS 上下载和检索本地文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42584718/