使用React Native下载数据文件以供脱机使用

我想开发一个应用程序,用户可以select不同的游戏包安装在他们的Android或iOS设备。 一个游戏包将包括:

  • 一个或多个JSON文件
  • 图片
  • 声音

现在,我并不担心这些文件是单独传输还是传输到一个zip文件中(尽pipezip文件肯定会是首选)。 当然,该设备将需要连接到互联网,以获得最新的游戏包列表,并下载用户select的游戏包。 一旦游戏包被下载到手机中,用户将不需要互联网连接来玩游戏,因为它们将具有所有文件。

我如何去执行这个在我的项目?

我如何下载文件? 我会使用react-native-fetch-blob库并将其保存在特定的位置吗? 这个库指的是将它保存为“caching”而不是永久的,所以我不确定这是否是正确的解决scheme。 我在库页面上看到的具体部分是“使用特定的文件path”。 但是,因为它是caching,我应该寻找更多的更长期存储的东西吗? 它确实说在页面上文件不会被删除,所以我有点困惑,在这种情况下永久存储和caching之间的区别是什么。

一旦文件被下载,我就可以打开图像并显示它们,打开声音文件并播放它们,打开json文件并处理它们?

查看React Native FS,特别是有关downloadFile:的文档downloadFile:

https://github.com/johanneslumpe/react-native-fs#downloadfileoptions-downloadfileoptions–jobid-number-promise-promisedownloadresult-

这是一个工作的例子:

 import React, { Component } from 'react'; import { AppRegistry, Text, View, Image, } from 'react-native'; import RNFS from 'react-native-fs'; export default class downloadFile extends Component { constructor() { super() this.state = { isDone: false, }; this.onDownloadImagePress = this.onDownloadImagePress.bind(this); } onDownloadImagePress() { RNFS.downloadFile({ fromUrl: 'https://facebook.github.io/react-native/img/header_logo.png', toFile: `${RNFS.DocumentDirectoryPath}/react-native.png`, }).promise.then((r) => { this.setState({ isDone: true }) }); } render() { const preview = this.state.isDone ? (<View> <Image style={{ width: 100, height: 100, backgroundColor: 'black', }} source={{ uri: `file://${RNFS.DocumentDirectoryPath}/react-native.png`, scale: 1 }} /> <Text>{`file://${RNFS.DocumentDirectoryPath}/react-native.png`}</Text> </View> ) : null; return ( <View> <Text onPress={this.onDownloadImagePress}>Download Image</Text> {preview} </View> ); } } AppRegistry.registerComponent('downloadFile', () => downloadFile); 

知道heightwidth必须在Image上设置很重要

在这里输入图像说明