加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何使用react native和react-native-fetch-blob在iOS上下载和检

发布时间:2020-12-15 20:11:19 所属栏目:百科 来源:网络整理
导读:我正在使用react-native-fetch-blob来下载mp3文件,然后再播放它们.问题是当我关闭应用程序并重新启动时,RNFetchBlob.fs.dirs.DocumentDir的实际路径发生了变化,这意味着我无法使用下载文件后立即存储的绝对文件路径,在下次运行时检索文件该应用程序. 这是我
我正在使用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上使用并将文件保存到我的应用程序目录中?或者我应该以任何其他方式设置文件路径?

我正在使用反应原生0.41.

解决方法

我做了以下更改以使其工作,至少现在在模拟器上.不确定在实际手机上会发生什么.

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读