15.8 C
London
Friday, June 7, 2024

react native – Expo background location monitoring for iOS in improvement construct


Because the title says, I am having points with background location monitoring for iOS.

I’m at present utilizing Expo’s inside improvement construct to run the app on my bodily iPhone gadget. When the app is within the foreground, the background activity runs as anticipated and my backend recieves the customers location. Nevertheless, once I exit the app the placement updates cease.

Is the problem with my code, or is it with the Expo improvement construct?

import { useEffect, useState, useCallback } from "react";
import * as Location from "expo-location";
import * as SecureStore from "expo-secure-store";
import * as TaskManager from "expo-task-manager";
import axios from "axios";
import { handleError } from "@/utils/handleError";

const LOCATION_TASK_NAME = "background-location-task";

TaskManager.defineTask(LOCATION_TASK_NAME, async ({ information, error }) => {
  if (error) {
    handleError(error, "Background location activity error");
    return;
  }
  console.log("Location activity triggered");

  if (information) {
    const { areas } = information as any;
    const [location] = areas;
    const { coords } = location;

    console.log("Location up to date", coords);

    const accessToken = await SecureStore.getItemAsync("accessToken");
    const uid = await SecureStore.getItemAsync("uid");

    if (accessToken && uid) {
      strive {
        await axios.submit(
          `${course of.env.EXPO_PUBLIC_API_ENDPOINT}/customers/${uid}/place`,
          {
            latitude: coords.latitude,
            longitude: coords.longitude,
          },
          {
            headers: {
              Authorization: `Bearer ${accessToken}`,
            },
          }
        );
      } catch (error) {
        handleError(error, "Didn't replace your place.");
      }
    }
  }
});

export const useLocation = () => {
  const [errorMsg, setErrorMsg] = useState<string | null>(null);
  const [foregroundStatus, requestForegroundPermission] =
    Location.useForegroundPermissions();
  const [backgroundStatus, requestBackgroundPermission] =
    Location.useBackgroundPermissions();

  const requestPermissions = useCallback(async () => {
    const foregroundStatusResult = await requestForegroundPermission();
    if (!foregroundStatusResult.granted) {
      setErrorMsg("Permission to entry location within the foreground was denied");
      return {
        foregroundStatus: foregroundStatusResult.standing,
        backgroundStatus: null,
      };
    }

    const backgroundStatusResult = await requestBackgroundPermission();
    if (!backgroundStatusResult.granted) {
      setErrorMsg("Permission to entry location within the background was denied");
    }
    return {
      foregroundStatus: foregroundStatusResult.standing,
      backgroundStatus: backgroundStatusResult.standing,
    };
  }, [requestForegroundPermission, requestBackgroundPermission]);

  const checkPermissions = useCallback(async () => {
    const foregroundStatusResult =
      await Location.getForegroundPermissionsAsync();
    const backgroundStatusResult =
      await Location.getBackgroundPermissionsAsync();

    return {
      foregroundStatus: foregroundStatusResult.standing,
      backgroundStatus: backgroundStatusResult.standing,
    };
  }, []);

  const startTracking = useCallback(async () => {
    if (!backgroundStatus?.granted) {
      setErrorMsg("Permission to entry location was denied");
      return;
    }

    console.log("Beginning location monitoring");

    await Location.startLocationUpdatesAsync(LOCATION_TASK_NAME, {
      accuracy: Location.Accuracy.Excessive,
      timeInterval: 10000, // Replace each 10 seconds
      distanceInterval: 10, // in meters
      foregroundService: {
        notificationTitle: "Location Monitoring",
        notificationBody: "We're monitoring your location within the background",
        notificationColor: "#FF0000",
      },
    });
  }, [backgroundStatus]);

  const stopTracking = useCallback(async () => {
    console.log("Stopping location monitoring");
    await Location.stopLocationUpdatesAsync(LOCATION_TASK_NAME);
  }, []);

  /*
  useEffect(() => {
    return () => {
      stopTracking();
    };
  }, [stopTracking]);
  */

  return {
    errorMsg,
    foregroundStatus,
    backgroundStatus,
    requestPermissions,
    checkPermissions,
    startTracking,
    stopTracking,
    permissionStatus: backgroundStatus?.standing,
  };
};


Latest news
Related news

LEAVE A REPLY

Please enter your comment!
Please enter your name here