我正在尝试获取IOS 14中的当前位置,但是当我签入EXPO时我没有任何回应 设置,那里没有显示位置权限。我已经检查了模拟器和物理设备。
挂钩代码
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;
};
响应
undefined
答案 0 :(得分:1)
docs says Location.getLastKnownPositionAsync()
可能返回 null:
返回解析为 LocationObject 类型的对象的承诺或 null 如果它不可用或不符合给定的要求,例如 最大年龄或要求的准确性。
所以你应该这样做:
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;
};