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

koj*_*ow7 6 android download ios react-native

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

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

现在我并不担心这些是单独传输还是以zip文件传输(虽然zip文件当然是首选).当然,设备需要连接到Internet才能获得当前的游戏包列表并下载用户选择的游戏包.一旦将游戏包下载到手机上,用户将不需要因特网连接来玩游戏,因为他们将拥有所有文件.

我如何在我的项目中实现这一点?

我该如何下载文件?我会使用react-native-fetch-blob库并将其保存在特定位置吗?该库是指将其保存为"缓存"而不是永久性,因此我不确定这是否是正确的解决方案.我在库页面上查看的特定部分是"使用特定文件路径".但是因为它是缓存,我应该寻找更长期存储的其他东西吗?它确实在页面上说文件不会被删除,所以我对在这种情况下永久存储和缓存之间的区别有点困惑.

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

pet*_*erp 11

查看React Native FS,特别是有关的文档 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);
Run Code Online (Sandbox Code Playgroud)

重要的是要知道height并且width必须设置在Image

在此输入图像描述