创建自定义挂钩以检索用户位置?

问题描述 投票:0回答:0

我在 SplashScreen 中使用这个钩子来检索用户位置信息。但是当我第一次使用 expo:run android 启动应用程序时,位置是未定义的。但在我按下“r”重新加载应用程序后,它运行良好。这是为什么?这是我的 useLocation 钩子代码:

export const useLocation = () => {
    const [locationPermissionInformation, requestPermission] = useForegroundPermissions();
    const [location, setLocation] = useState();
    const [error, setError] = useState();

    const verifyPermissions = async () => {
        if (locationPermissionInformation?.status === PermissionStatus.UNDETERMINED) {
            const permissions = await requestPermission();
            return permissions.granted;
        }
        if (locationPermissionInformation?.status === PermissionStatus.DENIED) {
            setError("You need to grant access to use this application!");
            return false;
        }
        return true;
    };

    const getLocation = async () => {
        const awaitPermission = await verifyPermissions();
        if (!awaitPermission) return;

        try {
            const locationUser = await getCurrentPositionAsync();
            setLocation(locationUser.coords);
            setError(null);
        } catch (error) {
            setError("Failed to get location. Please try again later.");
        }
    };

    useEffect(() => {
        getLocation();
    }, [locationPermissionInformation?.status]);

    return [location, error];
};
react-native location
© www.soinside.com 2019 - 2024. All rights reserved.