简体   繁体   English

expo-location 在 ios 中不起作用,并且在应用程序设置中不显示位置权限

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

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.我试图在 IOS 14 中获取当前位置,但我没有收到任何响应,当我检查 expo 设置时,它没有在那里显示位置权限。 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

The docs says Location.getLastKnownPositionAsync() might return null: 文档说Location.getLastKnownPositionAsync()可能返回 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.返回解析为 LocationObject 或 null 类型的对象的承诺,如果它不可用或不符合给定的要求,例如最大年龄或所需的准确性。

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;
};

use requestForegroundPermissionAsync() instead of requestPermissionAsync.使用 requestForegroundPermissionAsync() 而不是 requestPermissionAsync。 and the problem is solved.问题就解决了。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM