首页 > 解决方案 > react-native中iOS上的位置权限不起作用

问题描述

ios应用中没有弹出位置权限,也看不到应用设置中的权限选项

在安卓上运行良好。因为我可以使用 PermissionsAndroid 来获取权限。

通过查看其他答案,已经在 info.plist 中使用了以下选项。很少有答案只提到android。

info.plist

<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
    <string>Location Permission</string>
    <key>NSLocationAlwaysUsageDescription</key>
    <string>Location Permission</string>
    <key>NSLocationUsageDescription</key>
    <string>GPS data is required to...</string>
    <key>NSLocationWhenInUseUsageDescription</key>
    <string>Location Permission</string>

codeinthefile.js

try {
    const granted = await PermissionsAndroid.request(
        PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
        {
            title: "Geolocation Permission",
            message: "App needs access to your phone's location.",
        }
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
        Geolocation.getCurrentPosition(
            position => {
                Geocoder.from({
                    latitude: position.coords.latitude,
                    longitude: position.coords.longitude,
                })
                    .then(json => {
                        console.log(json);
                    })
                    .catch(error => {
                        console.log(error);
                    });
            },
            error => {
                console.log(error);
            },
            { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
        );
    } else {
        console.log('Location permission not granted!);
    }
} catch (err) {
    console.log('Location permission not granted!)
}

如果通过使用 info.plist 中的上述值,我应该可以访问位置,那么不应该出现未授予权限的错误。

标签: javascriptreact-nativegeolocation

解决方案


不要在iOS中使用PermissionAndroid,将权限要求放在info.plist中就足够了,

尝试类似的东西,

if(Platform.OS === "ios"){
   // your code using Geolocation and asking for authorisation with

   geolocation.requestAuthorization()
}else{
   // ask for PermissionAndroid as written in your code
}

推荐阅读