2017-03-03 20 views
1

我正在使用react-native-fetch-blob來下載mp3文件,然後再播放它們。問題是RNFetchBlob.fs.dirs.DocumentDir的實際路徑在我關閉應用程序並重新啓動時發生了變化,這意味着我無法使用下載文件後保存的絕對文件路徑在下次運行應用程序時檢索文件。如何通過反應本機和react-native-fetch-blob在iOS上下載和檢索本地文件?

這裏是我的下載和存儲的文件路徑代碼:

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 }爲持久的應用程序狀態的一部分。但是下次打開應用程序時cuz沒有用,文件路徑已被重新分配。例如,這裏的路徑中的一個文件被下載到: 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文件夾下。

顯然,音頻播放器(我使用的反應,本機的聲音)可以使用原始路徑,該應用程序已經存儲了未找到該文件。所以我的問題是:有沒有一種方法可以修復路徑?或者有沒有其他的方式來檢索我不知道的文件?

還有,我用我的電腦上的iOS模擬器。還沒有在手機上試過這個。有誰知道上述代碼是否可以直接在iPhone上使用,並將文件保存到我的應用程序的目錄?或者我應該用其他方式設置文件路徑嗎?

我使用反應原生0.41。

回答

2

我做了以下更改,使其工作,至少現在在模擬器上。不確定實際電話上發生了什麼。

當檢索該文件,而不是使用文件路徑由res.path()作爲返回如在上面的代碼,我現在直接使用filePath = RNFetchBlob.fs.dirs.DocumentDir + '/courseSections/' + sectionInfo.section.section_id + '.mp3'檢索文件時。

相關問題