Reputation: 966
EDIT: As of 9/12/2021, this method of requesting permissions has been depreciated for anything passed Expo SKD Version 40.
I am trying to request a user's location. I tried writing an async function to tell me if my request was processed, but it is ignored. I am prompted with a "location request" but I believe it is actually the Expo app and not my function.
Below is some of my code:
import React, { useState, useEffect, Component }from "react";
import { Permissions , Request } from 'expo-permissions'
//This is the async function I wrote to prompt the user to give permission
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');
}
}
//This logs the terminal and lets me know that the user's current location has been isolated (mounting). When the app no longer needs their location, it dismounts to prevent a memory leak.
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')
}
},
[],
),
)
Upvotes: 3
Views: 19775
Reputation: 254
Check this library for Permission on react-native
Here's https://www.npmjs.com/package/react-native-permissions.
For Android only there a default Package in react-native. ( PermissionAndroid)
https://reactnative.dev/docs/permissionsandroid
Update your manifest file also. Indicating that the application going to use external resource which requires user permission.
https://developer.android.com/guide/topics/manifest/uses-permission-element
And For iOS update info.plist file
https://www.iosdev.recipes/info-plist/permissions/
Upvotes: 5