确定地理定位是否启用了本机响应

Paw*_*weł 11 geolocation ios react-native

使用RN构建应用程序我使用以下内容来接收用户的位置:

 navigator.geolocation.getCurrentPosition(
  (position) => {
   //do stuff with location
  },
  (error) => {
    //error or locaiton not allowed
  },
  {enableHighAccuracy: true, timeout: 20000, maximumAge: 1000}
);
Run Code Online (Sandbox Code Playgroud)

其中立即调用用户的查询以接受地理定位权限.我现在想要实现的是在提示用户点击按钮接受这些权限之前有一个显式屏幕.为了实现这一目标,我需要一些方法来检查他是否已经接受了这些权限.在存储中缓存它将是一个糟糕的解决方案 - 如果用户更改设置中的权限,它可能会不同步.

如何在不触发权限警报的情况下检查用户是否已接受地理定位权限?

Mar*_*ini 9

您可以使用此库https://github.com/yonahforst/react-native-permissions来检查用户是否已接受位置许可.像这样:

Permissions.getPermissionStatus('location')
  .then(response => {
    this.setState({ locationPermission: response })
  })
Run Code Online (Sandbox Code Playgroud)

  • 请不要只是发布一些工具或库作为答案.至少在答案本身中演示[它如何解决问题](http://meta.stackoverflow.com/a/251605). (7认同)
  • 请编辑您的答案,不再更新 (3认同)
  • ^^我认为这是一个非常有用的答案。它确切地描述了如何解决该问题?! (2认同)

Man*_*ash 5

在 react-native-permissions 的 v2.xx ( https://github.com/react-native-community/react-native-permissions )

import { Platform } from "react-native";
import { PERMISSIONS, request } from "react-native-permissions";
import * as Geolocation from "@react-native-community/geolocation";

try {
request(
    Platform.select({
      android: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
      ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE
    })
  ).then(res => {
    if (res == "granted") {
      Geolocation.getCurrentPosition( // do location staffs);
      Geolocation.watchPosition( // do watch location staffs );
    } else {
      // console.log("Location is not enabled");
    }
  });
} catch (error) {
  console.log("location set error:", error);
}
Run Code Online (Sandbox Code Playgroud)