首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用react native和react-native-fetch-blob下载和检索iOS上的本地文件?

如何使用react native和react-native-fetch-blob下载和检索iOS上的本地文件?
EN

Stack Overflow用户
提问于 2017-03-04 01:07:17
回答 1查看 7.4K关注 0票数 6

我使用react-native-fetch-blob下载mp3文件,然后播放它们。问题是,当我关闭应用程序并重新启动时,RNFetchBlob.fs.dirs.DocumentDir的实际路径会发生变化,这意味着我不能使用下载文件后立即存储的绝对文件路径,在应用程序的下一次运行中检索文件。

下面是我下载和存储文件路径的代码:

代码语言:javascript
复制
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。

EN

回答 1

Stack Overflow用户

发布于 2017-03-04 07:39:34

我做了以下更改以使其正常工作,至少现在是在模拟器上。不知道在真正的手机上会发生什么。

在检索文件时,我不像上面的代码那样使用res.path()返回的文件路径,而是在检索文件时直接使用filePath = RNFetchBlob.fs.dirs.DocumentDir + '/courseSections/' + sectionInfo.section.section_id + '.mp3'

票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/42584718

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档