Quantcast
Channel: Active questions tagged react-native+ios - Stack Overflow
Viewing all articles
Browse latest Browse all 16552

Can't get background tasks to work in React-Native

$
0
0

I need to frequently write into a text file, let's say write a timestamp into a file with react-native in iOS and android. I wrote an app by the help of the following libraries. On android, the app is working perfectly fine, but on iOS not working properly.

I tried to use these libraries:

  1. react-native-background-task
  2. react-native-background-fetch
  3. react-native-background-queue + react-native-background-task

But none of them works fine:

  1. with react-native-background-task: the file is written randomly 5-6 times a day or less
  2. with react-native-background-fetch: the file is written randomly 3-4 times a day or less
  3. react-native-background-queue + react-native-background-task: the file is not written AT ALL!

Would you please tell me if these behaviors are normal, and if not, what am I doing wrong???

Any help would be greatly appreciated.

Here are my codes:

In order to use react-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>)
  }

}

In order to use react-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);
    } 
}          

};

In order to use react-native-background-queue + react-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,
  },
});

And here is 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;

Viewing all articles
Browse latest Browse all 16552

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>