如何在 React Native / Expo 中请求权限?

How to request permissions in React Native / Expo?

编辑:截至 2021 年 9 月 12 日,对于通过 Expo SKD 版本 40 的任何内容,这种请求权限的方法都已贬值。

我正在尝试请求用户的位置。我尝试编写一个异步函数来告诉我我的请求是否已被处理,但它被忽略了。我收到“位置请求”提示,但我相信它实际上是 Expo 应用程序,而不是我的功能。

下面是我的一些代码:

import React, { useState, useEffect, Component }from "react";

import { Permissions , Request } from 'expo-permissions'

//这是我写的提示用户给权限的async函数

async function getLocationAsync(){
  const { status, permissions } = await Permissions.askAsync( Permissions.LOCATION);
if (status === 'granted'){
console.log('It worked!')
} 
else {
  throw new Error('Location permission not granted');
  }
}

//这会记录终端并让我知道用户的当前位置已被隔离(挂载)。当应用程序不再需要它们的位置时,它会卸载以防止内存泄漏。

const Screen = ({navigation})=> { 
    const [user_latitude, setUserLatitude] = useState(0)
    const [user_longitude, setUserLongitude] = useState(0)
    const [position_error, setPositionError] = useState(null)


useFocusEffect( 
      React.useCallback(()=> {
        
      let isActive = true;

      const fetchGeoPosition = () => {
        navigator.geolocation.getCurrentPosition(
        position => { 
          if (isActive){

          setUserLatitude(position.coords.latitude);
          setUserLongitude(position.coords.longitude);
          setPositionError(null);


          console.log('Location Accessed')

          
        } 
        setIsLoading(false)

      }, 

      error => isActive && setPositionError(error.message),
      {enableHighAccuracy: true, timeout: 0, maximumAge: 1000} 
      ); 
    }

    fetchGeoPosition()

      return () =>{
        isActive = false
        console.log('Location Severed')
          }
        }, 
      [],
       ),
    )
    
 

检查这个库是否有 react-native 权限

这里是https://www.npmjs.com/package/react-native-permissions

对于Android,react-native 中只有一个默认包。 (权限Android)

https://reactnative.dev/docs/permissionsandroid

同时更新您的清单文件。表明应用程序将使用需要用户权限的外部资源。

https://developer.android.com/guide/topics/manifest/uses-permission-element

并为 iOS 更新 info.plist 文件

https://www.iosdev.recipes/info-plist/permissions/