Не удается заставить фоновые задачи работать в React-Native - PullRequest
1 голос
/ 02 октября 2019

Мне нужно часто записывать в текстовый файл, скажем, записывать временную метку в файл с Reaction-native в iOS и Android. Я написал приложение с помощью следующих библиотек. На андроиде приложение работает отлично, но на iOS не работает должным образом.

Я пытался использовать следующие библиотеки:

  1. реаги-native-background-task
  2. реакция-собственный-фон-выборка
  3. реакция-собственный-фон-очередь + реагировать-собственный-фон-task

Но ни один из них не работает нормально:

  1. с response-native-background-task: файл записывается случайным образом 5-6 раз в день илиМеньше
  2. с реакцией-родной-фоновой выборки: файл записывается случайным образом 3-4 раза в день или меньше
  3. реакция-нативной-фоновой очередью + реакция-нативной-фоновой задачей: файл не пишется ВСЕ!

Скажите, пожалуйста, нормальное ли это поведение, и если нет, то что я делаю неправильно ???

Любая помощь будетс благодарностью.

Вот мои коды:

Для того, чтобы использовать response-native-background-task :

import React from 'react'
import Mytest from './test';
import BackgroundTask from 'react-native-background-task'
import {
    Text,
    View,
  } from 'react-native';

BackgroundTask.define(() => {
  console.log('Hello from a background task')
  Mytest.writeFiles()
  BackgroundTask.finish()
})

export default class MyApp extends React.Component {

  componentDidMount() {
    BackgroundTask.schedule()
  }

  render() {
    return(
     <View>
      <Text>Hello world</Text>
    </View>)
  }

}

Дляиспользовать act-native-background-fetch :

import React, { Component } from 'react';
import {
    Text,
    View,
    StyleSheet
  } from 'react-native';
import BackgroundFetch from "react-native-background-fetch";

var RNFS = require('react-native-fs');
var path = RNFS.DocumentDirectoryPath + '/fetch.txt';
var count = 0

export default class App extends Component {

  constructor(props) {
    super(props);
    this.state = {
      date: '',
    }
  }

  componentDidMount() {
    BackgroundFetch.configure({
      stopOnTerminate: false,
      startOnBoot: true,
      requiredNetworkType: BackgroundFetch.NETWORK_TYPE_NONE,
      requiresCharging: false,      // Default
      requiresDeviceIdle: false,    // Default
      requiresBatteryNotLow: false, // Default
      requiresStorageNotLow: false  // Default
    }, () => {
      console.log("[js] Received background-fetch event");
      this.writeFiles()
      BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NEW_DATA);
    }, (error) => {
      console.log("[js] RNBackgroundFetch failed to start");
    });

    BackgroundFetch.status((status) => {
      switch(status) {
        case BackgroundFetch.STATUS_RESTRICTED:
          console.log("BackgroundFetch restricted");
          break;
        case BackgroundFetch.STATUS_DENIED:
          console.log("BackgroundFetch denied");
          break;
        case BackgroundFetch.STATUS_AVAILABLE:
          console.log("BackgroundFetch is enabled");
          break;
      }
    });
  }

  render() {
        return (
          <View style={styles.container}>
            <Text style={styles.welcome}>
              Welcome to React Native!
            </Text>
          </View>
        );
      }


  getDate() {
    var that = this;
    var date = new Date().getDate(); //Current Date
    var month = new Date().getMonth() + 1; //Current Month
    var year = new Date().getFullYear(); //Current Year
    var hours = new Date().getHours(); //Current Hours
    var min = new Date().getMinutes(); //Current Minutes
    var sec = new Date().getSeconds(); //Current Seconds
    that.setState({
      date:
        date + '/' + month + '/' + year + ' ' + hours + ':' + min + ':' + sec,
    });
  }


writeFiles = async () => {
  this.getDate()
    try {
      for(let i = 0; i < 1; i++){
        count = count + 1;
        console.log(count);
        RNFS.appendFile(path, '  \n  '+ count + '  \n  ' + this.state.date , 'utf8')
        .then((success) => {
        })
      }
    }catch (err) {
      console.warn("error", err);
    } 
}          

};

Чтобы использовать response-native-background-queue + реагировать-native-background-task :

import React, { Component } from 'react';
import Mytest from './test';
import BackgroundTask from 'react-native-background-task'
import {Platform,...} from 'react-native';
import queueFactory from 'react-native-queue';

BackgroundTask.define(async () => {
  queue = await queueFactory();
  queue.addWorker('background-example', async (id, payload) => {
  if (payload.name == 'sima') {
     Mytest.writeFiles()
     console.log('Hello from a background task ')}
  });
  await queue.start(20000); 
  BackgroundTask.finish();
});

export default class App extends Component<{}> {

  constructor(props) {
    super(props);

    this.state = {
      queue: null,
      data: null,
    };

    this.init();

  }

  async init() {
    const queue = await queueFactory();
    queue.addWorker('background-example', async (id, payload) => {
    });

    this.setState({
      queue
    });

  }

  componentDidMount() {
    BackgroundTask.schedule(); 
  }

  makeJob(jobName, payload = {}) {
    console.log('job is created but will not execute until the above OS background task runs in ~15 min');
    this.state.queue.createJob(jobName, payload, {
     timeout: 5000
    }, false); 
  }


  render() {
    let output = 'No data loaded from OS background task yet.';
    if (this.state.data) {
      output = JSON.stringify(this.state.data);
    }

    return (
      <View style={styles.container}>
        <Text style={styles.welcome}>
          Welcome to React Native!
        </Text>
        <Text>Click buttons below to add OS background task jobs.</Text>
        <Text>Then Close App (task will not fire if app is in focus).</Text>
        <Text>Job will exec in ~15 min in OS background.</Text>
        {this.state.queue && <Button title={"Press To Queue sima Job"} onPress={ () => { this.makeJob('background-example', { name: 'sima' }) } } /> }
        {this.state.queue && <Button title={"Press To Queue another Job"} onPress={ () => { this.makeJob('background-example', { name: 'simsim' }) } } /> }
        <Text>{output}</Text>
      </View>
    );

  }


}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#F5FCFF',
  },
  welcome: {
    fontSize: 20,
    textAlign: 'center',
    margin: 10,
  },
});

А вот и test.js:

var RNFS = require('react-native-fs');
var path = RNFS.DocumentDirectoryPath + '/test.txt';
var count = 0;

const Mytest = {

  writeFiles: () => {
    var that = this;
    var date = new Date().getDate(); //Current Date
    var month = new Date().getMonth() + 1; //Current Month
    var year = new Date().getFullYear(); //Current Year
    var hours = new Date().getHours(); //Current Hours
    var min = new Date().getMinutes(); //Current Minutes
    var sec = new Date().getSeconds(); //Current Seconds
    var date = date + '/' + month + '/' + year + ' ' + hours + ':' + min + ':' + sec

      try {
        for(let i = 0; i < 1; i++){
          count = count + 1;
          console.log(count);
          RNFS.appendFile(path, '  \n  '+ count + '  \n  ' + date , 'utf8')
          .then((success) => {
            console.log('FILE WRITTEN!');
          })
        }
      }catch (err) {
        console.warn("error", err);
      } 
  }
  }
  export default Mytest;
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...