expo-location not working in ios and not showing location permission in app settings

Viewed 1777

I am trying to get current location in IOS 14, but i am getting no response and when i check in expo settings it's not showing location permission there. I have checked in both simulator and physical device.

Hook Code

import { useEffect, useState } from "react";
import * as Location from "expo-location";

export default useLocation = () => {
  const [location, setLocation] = useState();

  const getLocation = async () => {
    try {
      const { granted } = await Location.requestPermissionsAsync();
      if (!granted) return;
      const {
        coords: { latitude, longitude },
      } = await Location.getLastKnownPositionAsync();
      setLocation({ latitude, longitude });
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getLocation();
  }, []);

  return location;
};

Response

undefined
1 Answers

The docs says Location.getLastKnownPositionAsync() might return null:

Returns a promise resolving to an object of type LocationObject or null if it's not available or doesn't match given requirements such as maximum age or required accuracy.

so you should do something like:

import { useEffect, useState } from "react";
import * as Location from "expo-location";

export default useLocation = () => {
  const [location, setLocation] = useState();

  const getLocation = async () => {
    try {
      const { granted } = await Location.requestPermissionsAsync();
      if (!granted) return;
      const last = await Location.getLastKnownPositionAsync();
      if (last) setLocation(last);
      else {
        const current = await Location.getCurrentPositionAsync();
        setLocation(current);
      }
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getLocation();
  }, []);

  return location;
};
Related