Code Monkey home page Code Monkey logo

react-native-background-fetch's Introduction

alt text Now with Expo support

react-native-background-fetch · npm npm

By Transistor Software, creators of React Native Background Geolocation


Background Fetch is a very simple plugin which attempts to awaken an app in the background about every 15 minutes, providing a short period of background running-time. This plugin will execute your provided callbackFn whenever a background-fetch event occurs.

There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible — you will never receive an event faster than 15 minutes. The operating-system will automatically throttle the rate the background-fetch events occur based upon usage patterns. Eg: if user hasn't turned on their phone for a long period of time, fetch events will occur less frequently or if an iOS user disables background refresh they may not happen at all.

🆕 Background Fetch now provides a scheduleTask method for scheduling arbitrary "one-shot" or periodic tasks.

iOS

  • There is no way to increase the rate which a fetch-event occurs and this plugin sets the rate to the most frequent possible — you will never receive an event faster than 15 minutes. The operating-system will automatically throttle the rate the background-fetch events occur based upon usage patterns. Eg: if user hasn't turned on their phone for a long period of time, fetch events will occur less frequently.
  • scheduleTask seems only to fire when the device is plugged into power.
  • ⚠️ When your app is terminated, iOS no longer fires events — There is no such thing as stopOnTerminate: false for iOS.
  • iOS can take days before Apple's machine-learning algorithm settles in and begins regularly firing events. Do not sit staring at your logs waiting for an event to fire. If your simulated events work, that's all you need to know that everything is correctly configured.
  • If the user doesn't open your iOS app for long periods of time, iOS will stop firing events.

Android


Contents


Installing the plugin

With Expo

$ npx expo install react-native-background-fetch

With yarn

$ yarn add react-native-background-fetch

With npm

$ npm install --save react-native-background-fetch

Setup Guides

Expo Setup

iOS Setup

Android Setup

Example

ℹ️ This repo contains its own Example App. See /example

import React from 'react';
import {
  SafeAreaView,
  StyleSheet,
  ScrollView,
  View,
  Text,
  FlatList,
  StatusBar,
} from 'react-native';

import {
  Header,
  Colors
} from 'react-native/Libraries/NewAppScreen';

import BackgroundFetch from "react-native-background-fetch";

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      events: []
    };
  }

  componentDidMount() {
    // Initialize BackgroundFetch ONLY ONCE when component mounts.
    this.initBackgroundFetch();
  }

  async initBackgroundFetch() {
    // BackgroundFetch event handler.
    const onEvent = async (taskId) => {
      console.log('[BackgroundFetch] task: ', taskId);
      // Do your background work...
      await this.addEvent(taskId);
      // IMPORTANT:  You must signal to the OS that your task is complete.
      BackgroundFetch.finish(taskId);
    }

    // Timeout callback is executed when your Task has exceeded its allowed running-time.
    // You must stop what you're doing immediately BackgroundFetch.finish(taskId)
    const onTimeout = async (taskId) => {
      console.warn('[BackgroundFetch] TIMEOUT task: ', taskId);
      BackgroundFetch.finish(taskId);
    }

    // Initialize BackgroundFetch only once when component mounts.
    let status = await BackgroundFetch.configure({minimumFetchInterval: 15}, onEvent, onTimeout);

    console.log('[BackgroundFetch] configure status: ', status);
  }

  // Add a BackgroundFetch event to <FlatList>
  addEvent(taskId) {
    // Simulate a possibly long-running asynchronous task with a Promise.
    return new Promise((resolve, reject) => {
      this.setState(state => ({
        events: [...state.events, {
          taskId: taskId,
          timestamp: (new Date()).toString()
        }]
      }));
      resolve();
    });
  }

  render() {
    return (
      <>
        <StatusBar barStyle="dark-content" />
        <SafeAreaView>
          <ScrollView
            contentInsetAdjustmentBehavior="automatic"
            style={styles.scrollView}>
            <Header />

            <View style={styles.body}>
              <View style={styles.sectionContainer}>
                <Text style={styles.sectionTitle}>BackgroundFetch Demo</Text>
              </View>
            </View>
          </ScrollView>
          <View style={styles.sectionContainer}>
            <FlatList
              data={this.state.events}
              renderItem={({item}) => (<Text>[{item.taskId}]: {item.timestamp}</Text>)}
              keyExtractor={item => item.timestamp}
            />
          </View>
        </SafeAreaView>
      </>
    );
  }
}

const styles = StyleSheet.create({
  scrollView: {
    backgroundColor: Colors.lighter,
  },
  body: {
    backgroundColor: Colors.white,
  },
  sectionContainer: {
    marginTop: 32,
    paddingHorizontal: 24,
  },
  sectionTitle: {
    fontSize: 24,
    fontWeight: '600',
    color: Colors.black,
  },
  sectionDescription: {
    marginTop: 8,
    fontSize: 18,
    fontWeight: '400',
    color: Colors.dark,
  },
});

export default App;

Executing Custom Tasks

In addition to the default background-fetch task defined by BackgroundFetch.configure, you may also execute your own arbitrary "oneshot" or periodic tasks (iOS requires additional Setup Instructions). However, all events will be fired into the Callback provided to BackgroundFetch#configure:

⚠️ iOS:

  • scheduleTask on iOS seems only to run when the device is plugged into power.
  • scheduleTask on iOS are designed for low-priority tasks, such as purging cache files — they tend to be unreliable for mission-critical tasks. scheduleTask will never run as frequently as you want.
  • The default fetch event is much more reliable and fires far more often.
  • scheduleTask on iOS stop when the user terminates the app. There is no such thing as stopOnTerminate: false for iOS.
// Step 1:  Configure BackgroundFetch as usual.
let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15
}, async (taskId) => {  // <-- Event callback
  // This is the fetch-event callback.
  console.log("[BackgroundFetch] taskId: ", taskId);

  // Use a switch statement to route task-handling.
  switch (taskId) {
    case 'com.foo.customtask':
      print("Received custom task");
      break;
    default:
      print("Default fetch task");
  }
  // Finish, providing received taskId.
  BackgroundFetch.finish(taskId);
}, async (taskId) => {  // <-- Task timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  BackgroundFetch.finish(taskId);
});

// Step 2:  Schedule a custom "oneshot" task "com.foo.customtask" to execute 5000ms from now.
BackgroundFetch.scheduleTask({
  taskId: "com.foo.customtask",
  forceAlarmManager: true,
  delay: 5000  // <-- milliseconds
});

API Documentation

Config

Common Options

@param {Integer} minimumFetchInterval [15]

The minimum interval in minutes to execute background fetch events. Defaults to 15 minutes. Note: Background-fetch events will never occur at a frequency higher than every 15 minutes. Apple uses a secret algorithm to adjust the frequency of fetch events, presumably based upon usage patterns of the app. Fetch events can occur less often than your configured minimumFetchInterval.

@param {Integer} delay (milliseconds)

ℹ️ Valid only for BackgroundFetch.scheduleTask. The minimum number of milliseconds in future that task should execute.

@param {Boolean} periodic [false]

ℹ️ Valid only for BackgroundFetch.scheduleTask. Defaults to false. Set true to execute the task repeatedly. When false, the task will execute just once.

Android Options

@config {Boolean} stopOnTerminate [true]

Set false to continue background-fetch events after user terminates the app. Default to true.

@config {Boolean} startOnBoot [false]

Set true to initiate background-fetch events when the device is rebooted. Defaults to false.

NOTE: startOnBoot requires stopOnTerminate: false.

@config {Boolean} forceAlarmManager [false]

By default, the plugin will use Android's JobScheduler when possible. The JobScheduler API prioritizes for battery-life, throttling task-execution based upon device usage and battery level.

Configuring forceAlarmManager: true will bypass JobScheduler to use Android's older AlarmManager API, resulting in more accurate task-execution at the cost of higher battery usage.

let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15,
  forceAlarmManager: true
}, async (taskId) => {  // <-- Event callback
  console.log("[BackgroundFetch] taskId: ", taskId);
  BackgroundFetch.finish(taskId);
}, async (taskId) => {  // <-- Task timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  BackgroundFetch.finish(taskId);
});
.
.
.
// And with with #scheduleTask
BackgroundFetch.scheduleTask({
  taskId: 'com.foo.customtask',
  delay: 5000,       // milliseconds
  forceAlarmManager: true,
  periodic: false
});

@config {Boolean} enableHeadless [false]

Set true to enable React Native's Headless JS mechanism, for handling fetch events after app termination.

  • 📂 index.js (MUST BE IN index.js):
import BackgroundFetch from "react-native-background-fetch";

let MyHeadlessTask = async (event) => {
  // Get task id from event {}:
  let taskId = event.taskId;
  let isTimeout = event.timeout;  // <-- true when your background-time has expired.
  if (isTimeout) {
    // This task has exceeded its allowed running-time.
    // You must stop what you're doing immediately finish(taskId)
    console.log('[BackgroundFetch] Headless TIMEOUT:', taskId);
    BackgroundFetch.finish(taskId);
    return;
  }
  console.log('[BackgroundFetch HeadlessTask] start: ', taskId);

  // Perform an example HTTP request.
  // Important:  await asychronous tasks when using HeadlessJS.
  let response = await fetch('https://reactnative.dev/movies.json');
  let responseJson = await response.json();
  console.log('[BackgroundFetch HeadlessTask] response: ', responseJson);

  // Required:  Signal to native code that your task is complete.
  // If you don't do this, your app could be terminated and/or assigned
  // battery-blame for consuming too much time in background.
  BackgroundFetch.finish(taskId);
}

// Register your BackgroundFetch HeadlessTask
BackgroundFetch.registerHeadlessTask(MyHeadlessTask);

@config {integer} requiredNetworkType [BackgroundFetch.NETWORK_TYPE_NONE]

Set basic description of the kind of network your job requires.

If your job doesn't need a network connection, you don't need to use this option as the default value is BackgroundFetch.NETWORK_TYPE_NONE.

NetworkType Description
BackgroundFetch.NETWORK_TYPE_NONE This job doesn't care about network constraints, either any or none.
BackgroundFetch.NETWORK_TYPE_ANY This job requires network connectivity.
BackgroundFetch.NETWORK_TYPE_CELLULAR This job requires network connectivity that is a cellular network.
BackgroundFetch.NETWORK_TYPE_UNMETERED This job requires network connectivity that is unmetered. Most WiFi networks are unmetered, as in "you can upload as much as you like".
BackgroundFetch.NETWORK_TYPE_NOT_ROAMING This job requires network connectivity that is not roaming (being outside the country of origin)

@config {Boolean} requiresBatteryNotLow [false]

Specify that to run this job, the device's battery level must not be low.

This defaults to false. If true, the job will only run when the battery level is not low, which is generally the point where the user is given a "low battery" warning.

@config {Boolean} requiresStorageNotLow [false]

Specify that to run this job, the device's available storage must not be low.

This defaults to false. If true, the job will only run when the device is not in a low storage state, which is generally the point where the user is given a "low storage" warning.

@config {Boolean} requiresCharging [false]

Specify that to run this job, the device must be charging (or be a non-battery-powered device connected to permanent power, such as Android TV devices). This defaults to false.

@config {Boolean} requiresDeviceIdle [false]

When set true, ensure that this job will not run if the device is in active use.

The default state is false: that is, the for the job to be runnable even when someone is interacting with the device.

This state is a loose definition provided by the system. In general, it means that the device is not currently being used interactively, and has not been in use for some time. As such, it is a good time to perform resource heavy jobs. Bear in mind that battery usage will still be attributed to your application, and shown to the user in battery stats.


Methods

Method Name Arguments Returns Notes
configure {FetchConfig}, callbackFn, timeoutFn Promise<BackgroundFetchStatus> Configures the plugin's callbackFn and timeoutFn. This callback will fire each time a background-fetch event occurs in addition to events from #scheduleTask. The timeoutFn will be called when the OS reports your task is nearing the end of its allowed background-time.
scheduleTask {TaskConfig} Promise<boolean> Executes a custom task. The task will be executed in the same Callback function provided to #configure.
status callbackFn Promise<BackgroundFetchStatus> Your callback will be executed with the current status (Integer) 0: Restricted, 1: Denied, 2: Available. These constants are defined as BackgroundFetch.STATUS_RESTRICTED, BackgroundFetch.STATUS_DENIED, BackgroundFetch.STATUS_AVAILABLE (NOTE: Android will always return STATUS_AVAILABLE)
finish String taskId Void You MUST call this method in your callbackFn provided to #configure in order to signal to the OS that your task is complete. iOS provides only 30s of background-time for a fetch-event -- if you exceed this 30s, iOS will kill your app.
start none Promise<BackgroundFetchStatus> Start the background-fetch API. Your callbackFn provided to #configure will be executed each time a background-fetch event occurs. NOTE the #configure method automatically calls #start. You do not have to call this method after you #configure the plugin
stop [taskId:String] Promise<boolean> Stop the background-fetch API and all #scheduleTask from firing events. Your callbackFn provided to #configure will no longer be executed. If you provide an optional taskId, only that #scheduleTask will be stopped.

Debugging

iOS

🆕 BGTaskScheduler API for iOS 13+

  • ⚠️ At the time of writing, the new task simulator does not yet work in Simulator; Only real devices.
  • See Apple docs Starting and Terminating Tasks During Development
  • After running your app in XCode, Click the [||] button to initiate a Breakpoint.
  • In the console (lldb), paste the following command (Note: use cursor up/down keys to cycle through previously run commands):
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateLaunchForTaskWithIdentifier:@"com.transistorsoft.fetch"]
  • Click the [ > ] button to continue. The task will execute and the Callback function provided to BackgroundFetch.configure will receive the event.

Simulating task-timeout events

  • Only the new BGTaskScheduler api supports simulated task-timeout events. To simulate a task-timeout, your fetchCallback must not call BackgroundFetch.finish(taskId):
let status = await BackgroundFetch.configure({
  minimumFetchInterval: 15
}, async (taskId) => {  // <-- Event callback.
  // This is the task callback.
  console.log("[BackgroundFetch] taskId", taskId);
  //BackgroundFetch.finish(taskId); // <-- Disable .finish(taskId) when simulating an iOS task timeout
}, async (taskId) => {  // <-- Event timeout callback
  // This task has exceeded its allowed running-time.
  // You must stop what you're doing and immediately .finish(taskId)
  print("[BackgroundFetch] TIMEOUT taskId:", taskId);
  BackgroundFetch.finish(taskId);
});
  • Now simulate an iOS task timeout as follows, in the same manner as simulating an event above:
e -l objc -- (void)[[BGTaskScheduler sharedScheduler] _simulateExpirationForTaskWithIdentifier:@"com.transistorsoft.fetch"]

Old BackgroundFetch API

  • Simulate background fetch events in XCode using Debug->Simulate Background Fetch
  • iOS can take some hours or even days to start a consistently scheduling background-fetch events since iOS schedules fetch events based upon the user's patterns of activity. If Simulate Background Fetch works, you can be sure that everything is working fine. You just need to wait.

Android

  • Observe plugin logs in $ adb logcat:
$ adb logcat *:S ReactNative:V ReactNativeJS:V TSBackgroundFetch:V
  • Simulate a background-fetch event on a device (insert <your.application.id>) (only works for sdk 21+:
$ adb shell cmd jobscheduler run -f <your.application.id> 999
  • Simulating scheduleTask events:
  1. Observe adb logcat for the registerTask log-entry and copy the jobId.
// from adb logcat *:S TSBackgroundFetch
TSBackgroundFetch: - registerTask: com.your.package.name (jobId: -359368280) <--
2. Now paste that `jobId` from logcat into the `adb shell` command to simulate a `JobScheduler` event:
```bash
$ adb shell cmd jobscheduler run -f com.your.package.name -359368280
  • For devices with sdk <21, simulate a "Headless JS" event with (insert <your.application.id>)
$ adb shell am broadcast -a <your.application.id>.event.BACKGROUND_FETCH

Licence

The MIT License

Copyright (c) 2013 Chris Scott, Transistor Software [email protected] http://transistorsoft.com

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

react-native-background-fetch's People

Contributors

almirfilho avatar christocracy avatar ckaznable avatar cogell avatar crowd-studio avatar davidpotter avatar djereg avatar emilios1995 avatar fmendoza avatar gponsu avatar jastanton avatar joaopiopedreira avatar lonnylot avatar lukasgjetting avatar macgregort avatar markholland avatar mcuelenaere avatar mikehardy avatar moox avatar mosch avatar olag1981 avatar pwellner avatar ragalie avatar rajgopalv avatar ridvanaltun avatar sbalay avatar teovillanueva avatar transistorsoft-pkg avatar trentlarson avatar zaubernerd avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-native-background-fetch's Issues

RCTEventEmitter.h file not found

i'm using
"react": "16.0.0",
"react-native": "^0.50.1",
dependencies

while building the project in xcode it filed with error

/Users/Admin/Projects/FlyerTeam/application/node_modules/react-native-background-fetch/ios/RNBackgroundFetch/RNBackgroundFetch.h:17:9: 'React/RCTEventEmitter.h' file not found

while i'm using that line in podfile
pod 'React', :path => '../node_modules/react-native'
it throws
[!] Unable to find a specification for yoga (= 0.50.1.React) depended upon by React/Core

Use with codepush

Is it possible to use react-native-background-fetch with codePush to update the app in background?

I've tried, the update is downloaded, but the app isn't. I'm probably missing something

Couldn't link framework (pods)

Couple issues with using cocoapods setup:

  1. I needed to include s.dependency 'React' in your podfile (gave you a PR for this)

  2. I needed to include: $(PROJECT_DIR)/../node_modules/react-native-background-fetch/ios/RNBackgroundFetch in my framework search paths, even though I believe that should have been handled by cocoapods... it does for RNBG not sure how this library is different.

Thoughts?

Oh and the error that happens if I don't do #1 is that it cannot find RCTBridgeModule.h in RNBackgroundFetch.h, and if I don't do number 2 it cannot find <TSBackgroundFetch/TSBackgroundFetch.h> in the category.

Background fetch failing on iOS 11 device

I had background fetch working fine up until today, no code has changed (that I can recall).

When simulating background refresh in XCode, it fires as expected and the relevant local push notifications are fired. However on an actual device, background refresh doesn't get activated at all, it's been over 20 hours and nothing, the app hasn't been force closed.

Is there anything that could prevent it from firing? Any way of looking into logs (for a release build) to find out?

It's not waking up while in background

Hello,

First thanks for your great work.

I followed your tutorial on how to install it. then I added your exact example to my app. which should wake up every 15 minutes and just run a console.log , but nothing is happening.

I've tried keeping app open in front, having it open in background, or completely closing it. it's happening ever. just runs once the app is loading. that's it.

Where is my mistake? I would really appreciate your help.

import React, {Component, PropTypes} from 'react';
import {
  ActivityIndicator,
  StyleSheet,
  Text,
  View,
  NetInfo,
  AlertIOS,
} from 'react-native';

var SQLite = require('react-native-sqlite-storage');
var Loading = require("./Loading");
var DeviceInfo = require('react-native-device-info');
import { Actions } from 'react-native-router-flux';
var LOADING = {};
var db = SQLite.openDatabase({name : "oc.db", location: 'default'});
import CodePush from "react-native-code-push";
import I18n from 'react-native-i18n';
import translations from './translations';
I18n.fallbacks = true;
let Functions = require('./Functions');
import BackgroundFetch from "react-native-background-fetch";

export default class Grab extends Component{
  constructor(props) {
        super(props);
        this.state = {
            isLoading: false,
            isConnected: null,
        };
    }

  componentWillMount() {

    NetInfo.isConnected.fetch().then(isConnected => {
      this.setState({
        isConnected: isConnected
      });
    });

    NetInfo.isConnected.addEventListener(
      'change',
      isConnected => {
        this.setState({
          isConnected: isConnected
        });
        this.sync();
      }
    );

    this.redirectUser();
  }

  componentDidMount(){
    BackgroundFetch.configure({
      stopOnTerminate: false
    }, function() {
      console.log("[js] Received background-fetch event");

      // To signal completion of your task to iOS, you must call #finish!
      // If you fail to do this, iOS can kill your app.
      BackgroundFetch.finish();
    }, function(error) {
      console.log("[js] RNBackgroundFetch failed to start");
    });

    BackgroundFetch.start(function(){
      console.log('[js] RNBackgroundFetch!');
      db.transaction((tx) => {
            tx.executeSql('INSERT INTO logs (time, message) VALUES (?, ?)', [Date(), 'Running!'], (tx, results) => {
                console.log(results);
              }, (err)=>{
                console.log(err);
              });
          });
    }, function(e){
      let error = 'Error!' + e;
      db.transaction((tx) => {
            tx.executeSql('INSERT INTO logs (time, message) VALUES (?, ?)', [Date(), error], (tx, results) => {
                console.log(results);
              }, (err)=>{
                console.log(err);
              });
          });
    });

  }

  toggleAllowRestart() {
    this.state.restartAllowed
      ? CodePush.disallowRestart()
      : CodePush.allowRestart();

    this.setState({ restartAllowed: !this.state.restartAllowed });
  }

  sync() {
  CodePush.sync(
    {
      installMode: CodePush.InstallMode.IMMEDIATE,
      updateDialog: false
    },
  );
}


  redirectUser(){
    Functions.GrabData((results)=> {
        Actions.tabbar({type: 'reset'});
    });
  }


  render() {

return(
    <View style={styles.container}><Loading/></View>
  );
  }

}

var styles = StyleSheet.create({
    container: {
      flex: 1,
      backgroundColor: "#fff",
      flexDirection: "column",
    },
});

Grab = CodePush(Grab);

Network fetch fails when triggered by Background-Fetch

The Background-Fetch works perfectly, but I sometime (I'd say 90% of the time) get an error from the fetch network library when my request is fired on the background:

TypeError: Network request failed

However when triggering the request manually it works 100% of the time.
Are there some known limitations about doing a http request with Backgroud-Fetch?

question about usage

What are the start and stop method for? They aren't mentioned in the example code.

upgrade problem: Undefined symbols for architecture arm64

I'm in the process of upgrading to RN0.42 and react-native-background-fetch 2.0.3. I'm getting this error, any ideas?

Undefined symbols for architecture arm64:
  "_OBJC_CLASS_$_AppDelegate", referenced from:
      l_OBJC_$_CATEGORY_AppDelegate_$_AppDelegate in RNBackgroundFetch+AppDelegate.o
  "_main", referenced from:
     implicit entry/start for main executable
ld: symbol(s) not found for architecture arm64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

Fetch fails to setup because "UI API called on a background thread"

Hey!

Thanks for the awesome module!

After installing as per the instructions, I'm unable to get the fetch to work, for some reason I keep getting the following in the logs once the app opens for the first time:

Main Thread Checker: UI API called on a background thread: -[UIApplication backgroundRefreshStatus]

The app is super simple:

class TestScreen extends Component {
  componentDidMount() {
    // Configure it.
    BackgroundFetch.configure({
      stopOnTerminate: false
    }, function() {
      console.log("[js] Received background-fetch event");

      // To signal completion of your task to iOS, you must call #finish!
      // If you fail to do this, iOS can kill your app.
      BackgroundFetch.finish();

    }, function(error) {
      console.log("[js] RNBackgroundFetch failed to start");
    });
  }

  render() {
    return(<Text>Hello World</Text>);
  }

I've tried the simulator using XCode (release build) and also with my device plugged in. On launch I get the following logs

2017-09-20 16:48:54.707999+0100 CPort[1751:514814] refreshPreferences: HangTracerEnabled: 0
2017-09-20 16:48:54.708050+0100 CPort[1751:514814] refreshPreferences: HangTracerDuration: 500
2017-09-20 16:48:54.708066+0100 CPort[1751:514814] refreshPreferences: ActivationLoggingEnabled: 0 ActivationLoggingTaskedOffByDA:0
2017-09-20 16:48:55.046559+0100 CPort[1751:514889] [TSBackgroundFetch configure]: {
    stopOnTerminate = 0;
}
=================================================================
Main Thread Checker: UI API called on a background thread: -[UIApplication backgroundRefreshStatus]
PID: 1751, TID: 514889, Thread name: (none), Queue name: com.facebook.react.RNBackgroundFetchQueue, QoS: 0
Backtrace:
4   CPort                     0x00000001026093f8 -[TSBackgroundFetch status] + 56
5   CPort                     0x0000000102609268 -[TSBackgroundFetch configure:] + 156
6   CPort                     0x00000001026badb4 -[RNBackgroundFetch configure:failure:] + 116
7   CoreFoundation                      0x000000018445b6a0 <redacted> + 144
8   CoreFoundation                      0x000000018433a820 <redacted> + 292
9   CoreFoundation                      0x000000018433f22c <redacted> + 60
10  CPort                     0x0000000102631184 -[RCTModuleMethod invokeWithBridge:module:arguments:] + 440
11  CPort                     0x000000010267e388 _ZN8facebook5react15RCTNativeModule11invokeInnerEjOKN5folly7dynamicE + 256
12  CPort                     0x000000010267e1f4 ___ZN8facebook5react15RCTNativeModule6invokeEjON5folly7dynamicEi_block_invoke + 52
13  libdispatch.dylib                   0x0000000102ccd49c _dispatch_call_block_and_release + 24
14  libdispatch.dylib                   0x0000000102ccd45c _dispatch_client_callout + 16
15  libdispatch.dylib                   0x0000000102cdc110 _dispatch_queue_serial_drain + 692
16  libdispatch.dylib                   0x0000000102cd09a4 _dispatch_queue_invoke + 332
17  libdispatch.dylib                   0x0000000102cdd104 _dispatch_root_queue_drain_deferred_wlh + 424
18  libdispatch.dylib                   0x0000000102ce4100 _dispatch_workloop_worker_thread + 652
19  libsystem_pthread.dylib             0x000000018407efe0 _pthread_wqthread + 932
20  libsystem_pthread.dylib             0x000000018407ec30 start_wqthread + 4
2017-09-20 16:48:55.054476+0100 CPort[1751:514889] [reports] Main Thread Checker: UI API called on a background thread: -[UIApplication backgroundRefreshStatus]
PID: 1751, TID: 514889, Thread name: (none), Queue name: com.facebook.react.RNBackgroundFetchQueue, QoS: 0
Backtrace:
4   CPort                     0x00000001026093f8 -[TSBackgroundFetch status] + 56
5   CPort                     0x0000000102609268 -[TSBackgroundFetch configure:] + 156
6   CPort                     0x00000001026badb4 -[RNBackgroundFetch configure:failure:] + 116
7   CoreFoundation                      0x000000018445b6a0 <redacted> + 144
8   CoreFoundation                      0x000000018433a820 <redacted> + 292
9   CoreFoundation                      0x000000018433f22c <redacted> + 60
10  CPort                     0x0000000102631184 -[RCTModuleMethod invokeWithBridge:module:arguments:] + 440
11  CPort                     0x000000010267e388 _ZN8facebook5react15RCTNativeModule11invokeInnerEjOKN5folly7dynamicE + 256
12  CPort                     0x000000010267e1f4 ___ZN8facebook5react15RCTNativeModule6invokeEjON5folly7dynamicEi_block_invoke + 52
13  libdispatch.dylib                   0x0000000102ccd49c _dispatch_call_block_and_release + 24
14  libdispatch.dylib                   0x0000000102ccd45c _dispatch_client_callout + 16
15  libdispatch.dylib                   0x0000000102cdc110 _dispatch_queue_serial_drain + 692
16  libdispatch.dylib                   0x0000000102cd09a4 _dispatch_queue_invoke + 332
17  libdispatch.dylib                   0x0000000102cdd104 _dispatch_root_queue_drain_deferred_wlh + 424
18  libdispatch.dylib                   0x0000000102ce4100 _dispatch_workloop_worker_thread + 652
19  libsystem_pthread.dylib             0x000000018407efe0 _pthread_wqthread + 932
20  libsystem_pthread.dylib             0x000000018407ec30 start_wqthread + 4
2017-09-20 16:48:55.232617+0100 CPort[1751:514889] [MC] System group container for systemgroup.com.apple.configurationprofiles path is /private/var/containers/Shared/SystemGroup/systemgroup.com.apple.configurationprofiles
2017-09-20 16:48:55.233718+0100 CPort[1751:514889] [MC] Reading from public effective user settings.
=================================================================
Main Thread Checker: UI API called on a background thread: -[UIApplication setMinimumBackgroundFetchInterval:]
PID: 1751, TID: 514889, Thread name: (none), Queue name: com.facebook.react.RNBackgroundFetchQueue, QoS: 0
Backtrace:
4   CPort                     0x00000001026096b4 -[TSBackgroundFetch start] + 108
5   CPort                     0x00000001026badcc -[RNBackgroundFetch configure:failure:] + 140
6   CoreFoundation                      0x000000018445b6a0 <redacted> + 144
7   CoreFoundation                      0x000000018433a820 <redacted> + 292
8   CoreFoundation                      0x000000018433f22c <redacted> + 60
9   CPort                     0x0000000102631184 -[RCTModuleMethod invokeWithBridge:module:arguments:] + 440
10  CPort                     0x000000010267e388 _ZN8facebook5react15RCTNativeModule11invokeInnerEjOKN5folly7dynamicE + 256
11  CPort                     0x000000010267e1f4 ___ZN8facebook5react15RCTNativeModule6invokeEjON5folly7dynamicEi_block_invoke + 52
12  libdispatch.dylib                   0x0000000102ccd49c _dispatch_call_block_and_release + 24
13  libdispatch.dylib                   0x0000000102ccd45c _dispatch_client_callout + 16
14  libdispatch.dylib                   0x0000000102cdc110 _dispatch_queue_serial_drain + 692
15  libdispatch.dylib                   0x0000000102cd09a4 _dispatch_queue_invoke + 332
16  libdispatch.dylib                   0x0000000102cdd104 _dispatch_root_queue_drain_deferred_wlh + 424
17  libdispatch.dylib                   0x0000000102ce4100 _dispatch_workloop_worker_thread + 652
18  libsystem_pthread.dylib             0x000000018407efe0 _pthread_wqthread + 932
19  libsystem_pthread.dylib             0x000000018407ec30 start_wqthread + 4
2017-09-20 16:48:55.236389+0100 CPort[1751:514889] [reports] Main Thread Checker: UI API called on a background thread: -[UIApplication setMinimumBackgroundFetchInterval:]
PID: 1751, TID: 514889, Thread name: (none), Queue name: com.facebook.react.RNBackgroundFetchQueue, QoS: 0
Backtrace:
4   CPort                     0x00000001026096b4 -[TSBackgroundFetch start] + 108
5   CPort                     0x00000001026badcc -[RNBackgroundFetch configure:failure:] + 140
6   CoreFoundation                      0x000000018445b6a0 <redacted> + 144
7   CoreFoundation                      0x000000018433a820 <redacted> + 292
8   CoreFoundation                      0x000000018433f22c <redacted> + 60
9   CPort                     0x0000000102631184 -[RCTModuleMethod invokeWithBridge:module:arguments:] + 440
10  CPort                     0x000000010267e388 _ZN8facebook5react15RCTNativeModule11invokeInnerEjOKN5folly7dynamicE + 256
11  CPort                     0x000000010267e1f4 ___ZN8facebook5react15RCTNativeModule6invokeEjON5folly7dynamicEi_block_invoke + 52
12  libdispatch.dylib                   0x0000000102ccd49c _dispatch_call_block_and_release + 24
13  libdispatch.dylib                   0x0000000102ccd45c _dispatch_client_callout + 16
14  libdispatch.dylib                   0x0000000102cdc110 _dispatch_queue_serial_drain + 692
15  libdispatch.dylib                   0x0000000102cd09a4 _dispatch_queue_invoke + 332
16  libdispatch.dylib                   0x0000000102cdd104 _dispatch_root_queue_drain_deferred_wlh + 424
17  libdispatch.dylib                   0x0000000102ce4100 _dispatch_workloop_worker_thread + 652
18  libsystem_pthread.dylib             0x000000018407efe0 _pthread_wqthread + 932
19  libsystem_pthread.dylib             0x000000018407ec30 start_wqthread + 4
2017-09-20 16:48:55.276659+0100 CPort[1751:514889] [TSBackgroundFetch start]
2017-09-20 16:48:55.276714+0100 CPort[1751:514889] [TSBackgroundFetch addListener]: RNBackgroundFetch
(lldb) 

If I then press home (to put the app in the background) and then simulate another Background App Refresh, an error occurs at the following line:

libsystem_kernel.dylib`mach_msg_trap:
    0x183f4cbbc <+0>: mov    x16, #-0x1f
    0x183f4cbc0 <+4>: svc    #0x80
->  0x183f4cbc4 <+8>: ret    

Do you have a working example I could use to compare against?

I'm using iOS 11 and the latest XCode.

Thanks

SIGSTOP Error

HI, thank for you plugin !

I've a little issue, when i want to simulate a background Fetch Xcode print this :

libsystem_kernel.dylib`mach_msg_trap:
    0x181bc721c <+0>: mov    x16, #-0x1f
    0x181bc7220 <+4>: svc    #0x80
->  0x181bc7224 <+8>: ret    
(Thread 1 : signal SIGSTOP)

Here my code :

 componentDidMount(){

    // NOTIFICATION
    PushNotification.configure({
    permissions: {
        alert: true,
        badge: true,
        sound: true
    },
    popInitialNotification: true,
    requestPermissions: true,
});

    //BACKGROUND FETCH
    // Configure it.
    BackgroundFetch.configure({
      stopOnTerminate: false
    }, function() {
      console.log("[js] Received background-fetch event");
      
      PushNotification.localNotificationSchedule({
        message: "Check out! 4 packages was released! 🎉", // (required)
        date: new Date(Date.now() + (2 * 1000)) // in 60 secs
      });
      // To signal completion of your task to iOS, you must call #finish!
      // If you fail to do this, iOS can kill your app.
      BackgroundFetch.finish();
    }, function(error) {
      console.log("[js] RNBackgroundFetch failed to start");
    });

    // Optional: Query the authorization status.
    BackgroundFetch.status(function(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;
      }
    });

        PushNotification.localNotificationSchedule({
        message: "Notification test", // (required)
        date: new Date(Date.now() + (10 * 1000)) // in 60 secs
      });
  } 

Do you have any idea?

Thank for your time! :)

Not working on device

Hi,
I have integrated the extension and it is working when I simulate background fetch from Xcode. it is not working when on device. I have waited 30 minutes but still I didnt receive any background fetch events. What could be missing?
Thanks

Crash app - Simulator 10 - Xcode 8

I install BG Fetch with React Native
"react": "15.4.1",
"react-native0cli": "1.3.0",
"react-native": "0.39.1",
"react-native-background-fetch": "^1.0.0"

It's can not when I run on Simulator and error.
screen shot 2016-12-09 at 00 22 16

If I remove -objC in Others Flag, It can run but crash.
screen shot 2016-12-09 at 00 22 42
screen shot 2016-12-09 at 00 24 53

How can I fix it? Please help me.
Thanks so much @transistorsoft @christocracy

how does this module work?

Can you please explain how this module works?
What I would like to know:

  1. How does the native module capture the js method to run?
  2. Can the callback method use variables outside of it? or must it be standalone?
  3. If yes, what happens when the app is killed? what happens to the variables? Is the entire js initialized? only the method?

thx!

Android Headless JS foreground crash

If the task runs while the app is in the foreground, the default behaviour is to crash the app, this can be disabled with a boolean in the 4th argument of HeadlessJsTaskConfig. I think that the library should expose this option in config, and if using the default value of false, it should not attempt the task if the app is in the foreground.

Changelog

Hi, thanks for creating this plugin 👍 I was about to upgrade the dependency, but I can't seem to find a changelog. Do you keep a release changelog anywhere?

Background fetch doesn't appear to fire

I'm using both the background fetch and background geolocation (independently).
My implementation for both sends data via Web Socket however it seems as if neither the portions are waking up my app and running in the background.

I've noticed in the demo geolocation app the RNBackgroundFetch+appdelegate.m file is in the ios directory and linked to the RNBackgroundGeolocationSample folder. The directions only instruct it to be linked. Could this be why?

Build error in xCode

After running react-native link I get the following when trying to build:

Undefined symbols for architecture x86_64:
  "_OBJC_CLASS_$_TSBackgroundFetch", referenced from:
      objc-class-ref in libRNBackgroundFetch.a(RNBackgroundFetch.o)
ld: symbol(s) not found for architecture x86_64
clang: error: linker command failed with exit code 1 (use -v to see invocation)

I've check that RNBackgroundFetch.xcodeproj is in Libraries, and libRNBackgroundFetch.a is in Build Phases / Link Binary With Libraries. Any idea what the issue is?

cannot simulate background fetch (launch due to background fetch event) with xcode 9

On xcode 8 with [email protected], I was able to trigger a background fetch in the simulator by going to Edit Scheme > Options > Checking "Launch due to background fetch event"

After upgrading to xcode 9, the background fetch no longer occurs on simulator start up. I tried updating the library to the latest [email protected] as well but the background fetch still does not get triggered.

The BackgroundFetch.status() function triggers though and says that it is enabled.

How can I test that this actually works now without downgrading back to xcode 8?

Lower power mode

Hi, first of all, thank for your module :-) !

But i 've a question, if Lower Power Mode is enable, the task will be running ? Or the task is disable during this mode?

Thanks!

requires async/promise to the registered function

Hi, I'm using this library and managed to get it working (thanks), in my case I needed to make some async tasks, but I found that if you don't return a promise or make the function async, it will terminate immediately. For example:

BackgroundFetch.configure({
      minimumFetchInterval: 15, 
      stopOnTerminate: false,
      startOnBoot: true        
    }, () => {
       setTimeout(() => {
          console.log("I will terminate now") // <--- never gets executed
          BackgroundFetch.finish();
       }, 5000);
       // --> since function returns undefined, stops immediately and never shows the log
    }, (error) => {
      console.log("[js] RNBackgroundFetch failed to start");
    });

// versus
BackgroundFetch.configure({
      minimumFetchInterval: 15, 
      stopOnTerminate: false,
      startOnBoot: true        
    }, () => {
       return Promise((resolve, reject) => { // <-- now it returns a promise
         setTimeout(() => {
           console.log("I will terminate now") // <--- gets executed
           BackgroundFetch.finish();
           resolve();
         }, 5000);
       });
    }, (error) => {
      console.log("[js] RNBackgroundFetch failed to start");
    });

So I don't know if this is expected, in case this is expected, I think it should be pointed out in the README file

TSBackgroundFetch WARNING: completionHandler is nil.

I can't make background fetch to start. I'm looking at the logs and seeing:

2017-03-26 01:59:18.843 [info][tid:com.facebook.react.RNBackgroundFetchQueue][RNBackgroundFetch.m:86] - RNBackgroundFetch finish
2017-03-26 01:59:18.843 MyTestApp[16348:248472] - TSBackgroundFetch WARNING: completionHandler is nil. No fetch event to finish. Ignored

I tried both referencing the appDelegate extension file and copying its content to the original file. neither of them seems to work.

I have latest Xcode, and I configured this module according to the manual tutorial.

Typescript 2.4.2 unable to detect module

I get the following error while performing an import

import BackgroundFetch from 'react-native-background-fetch'
error TS2307: Cannot find module 'react-native-background-fetch'

A naive solution is to copy the index.android.js file as index.js (so we have 3 files)

Any ideas what is being done wrong or does it need a PR?

Thanks!

how to check background is running?

i follow all step setup this module. but when i add example js code, this app log "BackgroundFetch is enabled". how to check and code when app run background?

request

@christocracy hey, sorry this isn't an issue at all - many thanks for building this project.

I am also using react-native-push-notifications, but I have a problem that I think is related to not calling the completion handler appropriately. I'm no iOS developer, not even good enough to competently copy what you've done here, but something very similar needs to be added to this project (zo0r/react-native-push-notification#263). I was wondering if you'd like to contribute?

Basically when remote push notification arrives your app has around 30 seconds to deal with it and then it needs call the completion handler. Sound familiar? The react-native-push-notification project is missing that round trip bit where the javascript code calls back to the native code in order to tell it to call the completion handler. Can you help?

Trying to understand when the code is executed

Thanks for open-sourcing this piece of code.
During testing this module I find my code is not executed when the user force quite the app.
Only when the app is in the background the code is executed and I'm able to test this with an emulator.

Can you confirm this is expected behaviour (I'm in the understanding that an closed app can run some code in the background, but maybe I'm totally wrong)?

error TSBackgroundFetch/TSBackgroundFetch.h' file not found

I followed in the installation instructions, but I'm getting this error in xCode (and also when I compile and run the app in iOS from the command line):

TSBackgroundFetch/TSBackgroundFetch.h' file not found

Is this my fault or a bug? How can I fix it?

Not fetching on closed app (stopOnTerminate: false)

Hello:

I seem to be having some issue making your module work, despite not seeing any sign of any errors and waited for now 4 hours and 10 minutes.

My app is has Background App Refresh enabled in the emulator settings of the app:

screen shot 2017-04-16 at 9 18 24 pm

Here is my package.json file:

  "dependencies": {
    "firebase": "^3.7.5",
    "react": "16.0.0-alpha.6",
    "react-native": "^0.43.3",
    "react-native-background-fetch": "^2.0.4"
  },
  "devDependencies": {
    "babel-jest": "19.0.0",
    "babel-preset-react-native": "1.9.1",
    "jest": "19.0.2",
    "react-test-renderer": "16.0.0-alpha.6"
  },

I have followed your instructions for the manual install and this is the code I use within one of my component:

  componentDidMount() {
    BackgroundFetch.configure({
      stopOnTerminate: false
    }, function() {
      console.log("[js] Received background-fetch event");
      Alert.alert(
        'BG fetched',
        'Received background-fetch event',
      );

      // function that pushes data to firebase
      this.setLocation( () => {
        Alert.alert(
          'BG fetched',
          'Fetched and setLocation!'
        );
        console.log("[js] Received background-fetch setLocation");
      } );

      Alert.alert(
        'BG fetched',
        'Fetched setTimeout!'
      );
      console.log("[js] Received background-fetch timeout call");
      setTimeout(() => BackgroundFetch.finish(), 5000);  // tried this due to potential asynchronousity.
    }, function(error) {
      console.log("[js] RNBackgroundFetch failed to start");
      Alert.alert(
        'BG fetch error',
        'Configure was not able to fetch',
        [
          {text: 'Ask me later', onPress: () => console.log('Ask me later pressed')},
          {text: 'Cancel', onPress: () => console.log('Cancel Pressed'), style: 'cancel'},
          {text: 'OK', onPress: () => console.log('OK Pressed')},
        ],
        { cancelable: false }
      );
    });

    // Optional: Query the authorization status.
    BackgroundFetch.status(function(status) {
      switch(status) {
        case BackgroundFetch.STATUS_RESTRICTED:
          console.log("BackgroundFetch restricted");
          Alert.alert(
            'BG fetch status',
            'BackgroundFetch restricted',
          );
          break;
        case BackgroundFetch.STATUS_DENIED:
          console.log("BackgroundFetch denied");
          Alert.alert(
            'BG fetch status',
            'BackgroundFetch denied',
          );
          break;
        case BackgroundFetch.STATUS_AVAILABLE:
          console.log("BackgroundFetch is enabled");
          Alert.alert(
            'BG fetch status',
            'BackgroundFetch is enabled'
          );
          break;
      }
    });
  }

And this is the only consoled data I get from the emulator:

Apr 16 17:05:04 112306745NB001 SpringBoard[25263]: [some.thing.JApp] Bootstrap complete with label: UIKitApplication:some.thing.JApp[0x171e][25268]
Apr 16 17:05:04 112306745NB001 CoreSimulatorBridge[25269]: [Common] [FBSSystemService][0xb126] Request successful: <BSProcessHandle: 0x7fb656513630; JApp:27554; valid: YES>
Apr 16 17:05:04 112306745NB001 CoreSimulatorBridge[25269]: Launch successful for 'some.thing.JApp'
Apr 16 17:05:04 112306745NB001 JApp[27554]: assertion failed: 16E195 14E269: libxpc.dylib + 64131 [624BAF4F-2E03-34F8-ACBA-970B04637786]: 0x7d
Apr 16 17:05:05 112306745NB001 JApp[27554]: - TSBackgroundFetch started
Apr 16 17:05:05 112306745NB001 JApp[27554]: - TSBackgroundFetch addListener: RNBackgroundFetch
Apr 16 17:05:07 112306745NB001 assertiond[25268]: client <BSProcessHandle: 0x7fec65406bb0; JApp:27554; valid: YES> HWM increased to 1 because of <BKProcessAssertion: 0x7fec65500ae0; "systemAnimationFence" (finishTask:180s); id:…ED075054483A>
Apr 16 17:05:16 112306745NB001 assertiond[25268]: client <BSProcessHandle: 0x7fec65406bb0; JApp:27554; valid: YES> HWM increased to 2 because of <BKProcessAssertion: 0x7fec65503840; "com.apple.asset_manager.cache_resource_cleanup" (finishTask:180s); id:…3DD77EEF7849>
Apr 16 17:05:16 112306745NB001 JApp[27554]: - TSBackgroundFetch onAppTerminate
Apr 16 17:05:16 112306745NB001 assertiond[25268]: Deleted job with label: UIKitApplication:some.thing.JApp[0x171e][25268]

My app was ran using: react-native run-ios --configuration Release

And upon launch I double clicked the home button and dragged the app up to clear it.

My assumption is that this should have still worked in the background and either a console log or an alert should have popped up on my screen. But neither of those things did.

Am I missing something? Or can the background refresh time be longer than 4 hours? its 9:25:45pm and emulator is still up and no new logs since.

Thank you for your help with this.

Changelog

Hi, I'd like to know what are the changes the new version (2.1.0) brings.
Having a changelog would be highly appreciated too.

Thanks for the awesome package!

Minimum interval not work

I have a troubleshoot when defined 15 minutes but seeing in log it occured in 2 times one long and one short.
My update is so crazy inteval 28 -> 2 -> 28 -> and again again and over again.

It happen in Android ios i dont test yet

follow my code example


try {
            BackgroundFetch.configure(
                {
                    minimumFetchInterval: 20,
                    stopOnTerminate: false,
                    startOnBoot: true
                }, async () => {
                    const currentDate = new Date();
                    const online = await isConnected();
                    if (online === false) {
                        console.log(`[js] Received command at ${currentDate.getHours()}:${currentDate.getMinutes()}`);
                        console.log('[js] Device is offline');
                        return BackgroundFetch.finish();
                    }
                    const hasUserLogged = await this.loadUser();
                    if (hasUserLogged !== null) {
                        console.log(`[js] Received command to update database at ${currentDate.getHours()}:${currentDate.getMinutes()}`);
                        const updateDatabase = new UpdateDatabase();
                        updateDatabase.setHost(hasUserLogged.data.host);
                        updateDatabase.setIndustry(hasUserLogged.data.industry);
                        updateDatabase.setLogin(hasUserLogged.data.login);
                        updateDatabase.setToken(hasUserLogged.data.token);
                        updateDatabase
                            .runAll()
                            .then(() => {
                                console.log('[js] database updated');
                                BackgroundFetch.finish();
                            })
                            .catch(error => {
                                console.log(`[js] Erro ao atualizar ${error}`);
                            });
                    }
                }, (error) => {
                    console.log(`[js] command failed to updated ${error}`);
                }
            );
        } catch (error) {
            console.log(`Not Logged ${error}`);
        }

Version 1.0.0 was not found on NPM

Hello, I am trying to install this library via pod command, but the version starts with zero doesn't provide a podspec file, however in this repository which is version one doesn't pushed to NPM yet.. When will be the code on NPM got updated? Thanks a lot.

react-native link fails in Xcode 9

I was having an issue with linking this framework as a part of a project using react-native-background-geolocation @2.9.2 so I was attempting to directly install this dependency (transistorsoft/react-native-background-geolocation#310 lead me to believe that there may have been some dependency issues, but in my case I'm doing a fresh install of the library so there shouldn't be any lingering old dependencies in node_modules, either way, I've deleting node_modules and re-installed a couple of times now :)

I'm having the following issue trying to install the library

$ npm i react-native-background-fetch --save
$ react-native link react-native-background-fetch
Scanning 847 folders for symlinks in /Users/adamhaney/Repos/new-spoon/node_modules (6ms)
rnpm-install info Linking react-native-background-fetch ios dependency 
rnpm-install info iOS module react-native-background-fetch has been successfully linked 
/Users/adamhaney/Repos/new-spoon/node_modules/xcode/lib/pbxProject.js:1586
    if (project.pbxGroupByName(group).path)
                                     ^

TypeError: Cannot read property 'path' of null
    at correctForPath (/Users/adamhaney/Repos/new-spoon/node_modules/xcode/lib/pbxProject.js:1586:38)
    at correctForPluginsPath (/Users/adamhaney/Repos/new-spoon/node_modules/xcode/lib/pbxProject.js:1572:12)
    at pbxProject.addPluginFile (/Users/adamhaney/Repos/new-spoon/node_modules/xcode/lib/pbxProject.js:89:5)
    at pbxProject.addSourceFile (/Users/adamhaney/Repos/new-spoon/node_modules/xcode/lib/pbxProject.js:149:21)
    at Object.<anonymous> (/Users/adamhaney/Repos/new-spoon/node_modules/react-native-background-fetch/scripts/postlink.js:95:9)
    at Module._compile (module.js:569:30)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)
    at Function.Module._load (module.js:458:3)
/Users/adamhaney/Repos/new-spoon/node_modules/react-native/local-cli/core/makeCommand.js:29
        throw new Error(`Error occured during executing "${command}" command`);
        ^

Error: Error occured during executing "node_modules/react-native-background-fetch/scripts/postlink.js" command
    at ChildProcess.prelink (/Users/adamhaney/Repos/new-spoon/node_modules/react-native/local-cli/core/makeCommand.js:29:15)
    at emitTwo (events.js:125:13)
    at ChildProcess.emit (events.js:213:7)
    at maybeClose (internal/child_process.js:921:16)
    at Process.ChildProcess._handle.onexit (internal/child_process.js:211:5)

Android support?

Just wondering what the timeline was for Android integration for the same sort of behavior of waking up the app at a regular-ish interval.

Seems like it may work well with React Native's headless-js

fetch every 60 sec

is it possible to fetch every 60 sec? I have a very small amount of data to post to a server and get response. the execution time is like 2-3 sec but I really want it to happen almost every minute.

change description

now it support both android and ios

iOS Background Fetch API Implementation

great job guys

Error: ENOENT: no such file or directory on postLink script

Just a heads up,

the iOS project filename is not always the same as the package.json project name.

packageManifest.name + '.xcodeproj',

This is the error I receive whenever react-native link runs:

return binding.open(pathModule._makeLong(path), stringToFlags(flags), mode);
                 ^

Error: ENOENT: no such file or directory, open '/Users/sudoplz/Development/Example/mobile/ios/acuitymobileapp.xcodeproj/project.pbxproj'
    at Object.fs.openSync (fs.js:652:18)
    at Object.fs.readFileSync (fs.js:553:33)
    at pbxProject.parseSync (/Users/sudoplz/Development/Example/mobile/node_modules/xcode/lib/pbxProject.js:44:28)
    at Object.<anonymous> (/Users/sudoplz/Development/Example/mobile/node_modules/react-native-background-fetch/scripts/postlink.js:42:58)
    at Module._compile (module.js:573:30)
    at Object.Module._extensions..js (module.js:584:10)
    at Module.load (module.js:507:32)
    at tryModuleLoad (module.js:470:12)
    at Function.Module._load (module.js:462:3)
    at Function.Module.runMain (module.js:609:10)

User's prime time hours

From the readme:

iOS Background Fetch is basically an API which wakes up your app about every 15 minutes (during the user's prime-time hours) and provides your app exactly 30s of background running-time

What does User's prime time hours actually mean?

My aim is to have an app that does a POST request (using fetch) every now and then (and I display the date when the latest request occured on screen). It works as expected on both the simulator and the device when I simulate a background fetch with XCode. However, I can see maybe only one or 2 requests a day, sometime none when I run the bundled app (in the background) during the day.
Any ideas on that one? Am I doing something wrong?

Broken link on INSTALL.md

A link in the bottom of the INSTALL.md file broken. In the docs directory, there is no README.md file.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.