React Native 未授予位置权限

location permission not granted in react native

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

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

他们显示未授予位置权限

首先获得用户的位置许可。使用这个功能

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

以上答案不再有效,因为 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...
    }
  }
}

请这样做

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

if (Platform.OS === 'android') {
  const granted = await PermissionsAndroid.request(
    PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
  );
  if (granted === PermissionsAndroid.RESULTS.GRANTED) {
    _getCourts();
  }
}

}

UsmanJ 是正确的,但有一个错误。 这是修复:

更改此行:if (granted === PermissionsAndroid.RESULTS.GRANTED) {

至:if ("granted" === PermissionsAndroid.RESULTS.GRANTED) {