在本机反应中未授予位置权限

And*_*han 1 react-native react-native-android

我在寻找位置时遇到了一个小问题,这是我的代码

export default class  App extends React.Component{
  state = {
        location: null
    };

    findCoordinates = () => {
        Geolocation.getCurrentPosition(
            position => {
                const location = JSON.stringify(position);
                this.setState({ location });
            },
      error => Alert.alert(error.message),
      { enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
    );
    };
  render(){
    return (
      <View style={styles.container}>
                <TouchableOpacity onPress={this.findCoordinates}>
                    <Text style={styles.welcome}>Find My Coords?</Text>
                    <Text>Location: {this.state.location}</Text>
                </TouchableOpacity>
            </View>
    );
  }
}
Run Code Online (Sandbox Code Playgroud)

他们显示未授予位置许可

Usm*_*anJ 8

上面的答案不再有效,因为该setRNConfiguration 函数现已弃用。

这是获取用户使用位置权限的更新方法:

import { Platform, PermissionsAndroid } from 'react-native';
import Geolocation from 'react-native-geolocation-service';

async function requestPermissions() {
  if (Platform.OS === 'ios') {
    const auth = await Geolocation.requestAuthorization("whenInUse");
    if(auth === "granted") {
       // do something if granted...
    }
  }

  if (Platform.OS === 'android') {
    await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
    );
    if (granted === PermissionsAndroid.RESULTS.GRANTED) {
      // do something if granted...
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 你能告诉我 if (granted === PermissionsAndroid.RESULTS.GRANTED) {} 中的“授予”在哪里吗 (2认同)

Aur*_*ana 7

首先从用户获取位置许可。使用这个功能

import { Platform, PermissionsAndroid } from 'react-native';

import Geolocation from 'react-native-geolocation-service';

async function requestPermissions() {
  if (Platform.OS === 'ios') {
    Geolocation.requestAuthorization();
    Geolocation.setRNConfiguration({
      skipPermissionRequests: false,
     authorizationLevel: 'whenInUse',
   });
  }

  if (Platform.OS === 'android') {
    await PermissionsAndroid.request(
      PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
    );
  }
}
Run Code Online (Sandbox Code Playgroud)