title: Can't get background tasks to work in React-Native
body: <p>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 <strong>iOS</strong> not working properly.</p>
  
  <p>I tried to use these libraries:</p>
  
  <ol>
  <li><a href="https://github.com/jamesisaac/react-native-background-task" rel="noreferrer">react-native-background-task</a></li>
  <li><a href="https://github.com/transistorsoft/react-native-background-fetch" rel="noreferrer">react-native-background-fetch</a></li>
  <li><a href="https://github.com/billmalarky/react-native-queue" rel="noreferrer">react-native-background-queue + react-native-background-task</a></li>
  </ol>
  
  <p>But none of them works fine:</p>
  
  <ol>
  <li>with react-native-background-task: the file is written randomly 5-6
  times a day or less</li>
  <li>with react-native-background-fetch: the file is written randomly 
  3-4 times a day or less</li>
  <li>react-native-background-queue + react-native-background-task: the
  file is not written AT ALL!</li>
  </ol>
  
  <p>Would you please tell me if these behaviors are normal, and if not, what am I doing wrong???</p>
  
  <p>Any help would be greatly appreciated.</p>
  
  <p>Here are my codes:</p>
  
  <p>In order to use <strong>react-native-background-task</strong>:</p>
  
  <pre><code>import React from 'react'
  import Mytest from './test';
  import BackgroundTask from 'react-native-background-task'
  import {
      Text,
      View,
    } from 'react-native';
  
  BackgroundTask.define(() =&gt; {
    console.log('Hello from a background task')
    Mytest.writeFiles()
    BackgroundTask.finish()
  })
  
  export default class MyApp extends React.Component {
  
    componentDidMount() {
      BackgroundTask.schedule()
    }
  
    render() {
      return(
       &lt;View&gt;
        &lt;Text&gt;Hello world&lt;/Text&gt;
      &lt;/View&gt;)
    }
  
  }
  </code></pre>
  
  <p>In order to use <strong>react-native-background-fetch</strong>:</p>
  
  <pre><code>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
      }, () =&gt; {
        console.log("[js] Received background-fetch event");
        this.writeFiles()
        BackgroundFetch.finish(BackgroundFetch.FETCH_RESULT_NEW_DATA);
      }, (error) =&gt; {
        console.log("[js] RNBackgroundFetch failed to start");
      });
  
      BackgroundFetch.status((status) =&gt; {
        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 (
            &lt;View style={styles.container}&gt;
              &lt;Text style={styles.welcome}&gt;
                Welcome to React Native!
              &lt;/Text&gt;
            &lt;/View&gt;
          );
        }
  
  
    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 () =&gt; {
    this.getDate()
      try {
        for(let i = 0; i &lt; 1; i++){
          count = count + 1;
          console.log(count);
          RNFS.appendFile(path, '  \n  '+ count + '  \n  ' + this.state.date , 'utf8')
          .then((success) =&gt; {
          })
        }
      }catch (err) {
        console.warn("error", err);
      } 
  }          
  
  };
  </code></pre>
  
  <p>In order to use <strong>react-native-background-queue + react-native-background-task</strong>:</p>
  
  <pre><code>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 () =&gt; {
    queue = await queueFactory();
    queue.addWorker('background-example', async (id, payload) =&gt; {
    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&lt;{}&gt; {
  
    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) =&gt; {
      });
  
      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 (
        &lt;View style={styles.container}&gt;
          &lt;Text style={styles.welcome}&gt;
            Welcome to React Native!
          &lt;/Text&gt;
          &lt;Text&gt;Click buttons below to add OS background task jobs.&lt;/Text&gt;
          &lt;Text&gt;Then Close App (task will not fire if app is in focus).&lt;/Text&gt;
          &lt;Text&gt;Job will exec in ~15 min in OS background.&lt;/Text&gt;
          {this.state.queue &amp;&amp; &lt;Button title={"Press To Queue sima Job"} onPress={ () =&gt; { this.makeJob('background-example', { name: 'sima' }) } } /&gt; }
          {this.state.queue &amp;&amp; &lt;Button title={"Press To Queue another Job"} onPress={ () =&gt; { this.makeJob('background-example', { name: 'simsim' }) } } /&gt; }
          &lt;Text&gt;{output}&lt;/Text&gt;
        &lt;/View&gt;
      );
  
    }
  
  
  }
  
  const styles = StyleSheet.create({
    container: {
      flex: 1,
      justifyContent: 'center',
      alignItems: 'center',
      backgroundColor: '#F5FCFF',
    },
    welcome: {
      fontSize: 20,
      textAlign: 'center',
      margin: 10,
    },
  });
  </code></pre>
  
  <p>And here is test.js:</p>
  
  <pre><code>var RNFS = require('react-native-fs');
  var path = RNFS.DocumentDirectoryPath + '/test.txt';
  var count = 0;
  
  const Mytest = {
  
    writeFiles: () =&gt; {
      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 &lt; 1; i++){
            count = count + 1;
            console.log(count);
            RNFS.appendFile(path, '  \n  '+ count + '  \n  ' + date , 'utf8')
            .then((success) =&gt; {
              console.log('FILE WRITTEN!');
            })
          }
        }catch (err) {
          console.warn("error", err);
        } 
    }
    }
    export default Mytest;
  </code></pre>