簡體   English   中英

React Native 背景下載

[英]React Native Background Download

我即將構建一個在本地存儲多個 MySqlite *.db 文件的應用程序。 這些用於用數據填充應用程序。

該應用程序應定期檢查這些文件之一是否有更新版本,如果有,請下載並替換該文件的舊版本。 此更新過程應在后台進行,而應用程序處於非活動狀態甚至關閉狀態。

我見過幾個插件,可以用來在后台執行任務(比如https://www.npmjs.com/package/react-native-background-task )。 這可用於定期檢查更新,但 iOS 上 30 秒的時間限制可能不足以下載 *.db 文件。 此外,該插件強制要求最低 Android API 版本為 21。

我的問題是:是否可以在后台輪詢更新並下載它們,替換舊文件?

我發現了一些有用的插件。

1. react-native-fetch-blob

https://github.com/wkh237/react-native-fetch-blob/wiki/Classes#rnfetchblobconfig

它有IOSBackgroundTask選項。

RNFetchBlob
.config({
  path : dest_file_path,
  IOSBackgroundTask: true,
  overwrite: true,
  indicator: true,
})
.fetch('GET', download_url, {
  //some headers ..
})
.progress( (received, total) => {
    console.log('progress : '+ received + ' / ' + total);
})
.then((res) => {
  console.log('# The file saved to :', file_path);
})

順便說一句,它看起來不能正常工作。 不確定我是否錯過了什么......

2. react-native-fs

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

  const ret = RNFS.downloadFile({
    fromUrl: download_url, 
    toFile: dest_file_path,
    connectionTimeout: 1000 * 10,
    background: true,
    discretionary: true,
    progressDivider: 1, 
    resumable: (res) => {
      console.log("# resumable :", res);
    },
    begin: (res) => {
        // start event
    }, 
    progress: (data) => {
        const percentage = ((100 * data.bytesWritten) / data.contentLength) | 0;
        console.log("# percentage :", percentage);
    },
  });

  jobId = ret.jobId;

  ret.promise.then((res) => {
    console.log('Download finished.');
    RNFS.completeHandlerIOS(jobId);
    jobId = -1;
  }).catch(err => {
    console.log('error');
    jobId = -1;
  });

它看起來運行良好。
順便說一下,當我嘗試通過推送通知在后台下載時,除非我打開應用程序,否則它不會開始下載。
任何人都可以解決這個問題?

對於后台下載,我用過的最好的模塊是react-native-background-downloader ,它有暫停、恢復和下載百分比。

import RNBackgroundDownloader from 'react-native-background-downloader';

let task = RNBackgroundDownloader.download({
    id: 'dbfile',
    url: 'https://link-to-db/MySqlite.db'
    destination: `${RNBackgroundDownloader.directories.documents}/MySqlite.db`
}).begin((expectedBytes) => {
    console.log(`Going to download ${expectedBytes} bytes!`);
}).progress((percent) => {
    console.log(`Downloaded: ${percent * 100}%`);
}).done(() => {
    console.log('Download is done!');
}).error((error) => {
    console.log('Download canceled due to error: ', error);
});

// Pause the task
task.pause();

// Resume after pause
task.resume();

// Cancel the task
task.stop();

此模塊也適用於iOS,您可以在后台連續下載多個文件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM