Geofencing Task doesn't run in React Native application

424 views Asked by At

I've created the function setGeofences to run at the start of the app to run a geofencing task.

I've added the function isGeoRunning to a button for checking if the task is running. It always returns false, meaning task is not running.

No errors or warnings given. I've followed the official instructions given here.

What am I doing wrong?

import React, { useState, useEffect } from 'react';
import { StyleSheet, Text, View, Dimensions, Button } from 'react-native';
import MapView, { Marker } from 'react-native-maps';
import * as Location from 'expo-location';
import { Audio } from 'expo-av';
import * as TaskManager from 'expo-task-manager';

const App = () => {

  const [region, setRegion] = useState({
    latitude: 59.334591,
    longitude: 18.063240,
    latitudeDelta: 0.4,
    longitudeDelta: 0.4
  });
  
  let [regions, setRegions] = useState([
    {
      title: "Test",
      latitude: 59.334591,
      longitude: 18.063240,
      radius: 100,
    }]);

  function setGeofences(){
    TaskManager.defineTask("Task1", ({ data: { eventType, regions }, error }) => {
      if (error) {
        console.log(error.message)
        alert(error.message)
        return;
      }
      if (eventType === LocationGeofencingEventType.Enter) {
        console.log("You've entered region:", region);
        alert("You've entered region:", region)
      } else if (eventType === LocationGeofencingEventType.Exit) {
        console.log("You've left region:", region);
        alert("You've left region:", region)
      }
    });
  }

  async function isGeoRunning(){
    await Location.hasStartedGeofencingAsync("Task1")
      .then((data) => alert(data))
    await TaskManager.isTaskRegisteredAsync("Task1")
      .then((data) => alert(data))
  }

  useEffect(() => {
  setGeofences()
  }, []) // Runs only once.

  return (
    <MapView
      style={{ flex: 1 }}
      region={region}
      onRegionChangeComplete={region => setRegion(region)}
    >

    <Button
      style="styleButton"
      title="checkRegion()"
      onPress={ () => { isGeoRunning() } }
      />
    ))}

    </MapView>
  );
};

export default App;
1

There are 1 answers

0
Swampy On

I had totally misunderstood the documentation. I'm not supposed to use the function this way. I'm only supposed to run:

Location.startGeofencingAsync("Task1", regions)