No Location Permission pop up in ios app nor can see Permissions options in the settings of the App
Works fine on Android. As I can use PermissionsAndroid to get the permissions.
Already used the following options in the info.plist by looking at the other answers. Few answers only mentioned about android.
info.plist
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key>
<string>Location Permission</string>
<key>NSLocationAlwaysUsageDescription</key>
<string>Location Permission</string>
<key>NSLocationUsageDescription</key>
<string>GPS data is required to...</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>Location Permission</string>
codeinthefile.js
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: "Geolocation Permission",
message: "App needs access to your phone's location.",
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
Geolocation.getCurrentPosition(
position => {
Geocoder.from({
latitude: position.coords.latitude,
longitude: position.coords.longitude,
})
.then(json => {
console.log(json);
})
.catch(error => {
console.log(error);
});
},
error => {
console.log(error);
},
{ enableHighAccuracy: true, timeout: 15000, maximumAge: 10000 }
);
} else {
console.log('Location permission not granted!);
}
} catch (err) {
console.log('Location permission not granted!)
}
If by using the above-mentioned values in info.plist I should get the access to location then there should not be an error of no permission granted.
Don't use PermissionAndroid in iOS, is enough to put the permission requirement in the info.plist,
try something like,
if(Platform.OS === "ios"){
// your code using Geolocation and asking for authorisation with
geolocation.requestAuthorization()
}else{
// ask for PermissionAndroid as written in your code
}
Thank you, Doug and David, Based on your suggestion I have made then changes to my code in the following way which worked for me:
if(Platform.OS === 'ios'){
Geolocation.requestAuthorization();
this.getGeoLocation();
}else {
let granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: "App Geolocation Permission",
message: "App needs access to your phone's location.",
}
);
if (androidGranted === PermissionsAndroid.RESULTS.GRANTED) {
this.getGeoLocation();
} else {
console.log('Location permission not granted!!!!');
}
}
Use below for both android and ios permissions .
import {Platform} from 'react-native';
import {request, PERMISSIONS, RESULTS} from 'react-native-permissions';
....
export async function getLocationPermissions() {
const granted = await request(
Platform.select({
android: PERMISSIONS.ANDROID.ACCESS_COARSE_LOCATION,
ios: PERMISSIONS.IOS.LOCATION_WHEN_IN_USE,
}),
{
title: 'DemoApp',
message: 'DemoApp would like access to your location ',
},
);
return granted === RESULTS.GRANTED;
}
....
// usage
const granted = await getLocationPermissions();
Related
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')
}
},
[],
),
)
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/
I'm pretty new to react and I'm trying to implement a service worker at the moment.
Actually I always get an error 'Uncaught SyntaxError: Unexpected token 'export'' in my "serviceworker.js" class.
Here's my main.tsx file.
import React from 'react';
import ReactDOM from 'react-dom';
import 'bootstrap/dist/css/bootstrap.css';
import App from './app/app';
import * as registerServiceWorker from './serviceworker/serviceworker';
ReactDOM.render(<App />, document.getElementById('root'));
registerServiceWorker.register();
And thats my "serviceworker.js" file.
const isLocalhost = Boolean(
window.location.hostname === 'localhost' ||
// [::1] is the IPv6 localhost address.
window.location.hostname === '[::1]' ||
// 127.0.0.1/8 is considered localhost for IPv4.
window.location.hostname.match(
/^127(?:\.(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)){3}$/
)
)
export function register(config) {
if ('serviceWorker' in navigator) {
// The URL constructor is available in all browsers that support SW.
// const publicUrl = new URL(process.env.PUBLIC_URL, window.location.href);
// if (publicUrl.origin !== window.location.origin) {
// // Our service worker won't work if PUBLIC_URL is on a different origin
// // from what our page is served on. This might happen if a CDN is used to
//
// return;
// }
window.addEventListener('load', () => {
const swUrl = `/serviceworker/serviceworker.js`;
if (isLocalhost) {
// This is running on localhost. Let's check if a service worker still exists or not.
checkValidServiceWorker(swUrl, config);
// Add some additional logging to localhost, pointing developers to the
// service worker/PWA documentation.
navigator.serviceWorker.ready.then(() => {
console.log(
'This web app is being served cache-first by a service ' +
'worker. To learn more, '
);
});
} else {
// Is not localhost. Just register service worker
registerValidSW(swUrl, config);
}
});
}
}
function registerValidSW(swUrl, config) {
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
if (installingWorker == null) {
return;
}
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the updated precached content has been fetched,
// but the previous service worker will still serve the older
// content until all client tabs are closed.
console.log(
'New content is available and will be used when all ' +
'tabs for this page are closed. See /CRA-PWA.'
);
// Execute callback
if (config && config.onUpdate) {
config.onUpdate(registration);
}
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
console.log('Content is cached for offline use.');
// Execute callback
if (config && config.onSuccess) {
config.onSuccess(registration);
}
}
}
};
};
})
.catch(error => {
console.error('Error during service worker registration:', error);
});
}
function checkValidServiceWorker(swUrl, config) {
// Check if the service worker can be found. If it can't reload the page.
fetch(swUrl)
.then(response => {
// Ensure service worker exists, and that we really are getting a JS file.
const contentType = response.headers.get('content-type');
if (
response.status === 404 ||
(contentType === null)
) {
// No service worker found. Probably a different app. Reload the page.
navigator.serviceWorker.ready.then(registration => {
registration.unregister().then(() => {
window.location.reload();
});
});
} else {
// Service worker found. Proceed as normal.
registerValidSW(swUrl, config);
}
})
.catch(() => {
console.log(
'No internet connection found. App is running in offline mode.'
);
});
}
export function unregister() {
if ('serviceWorker' in navigator) {
navigator.serviceWorker.ready.then(registration => {
registration.unregister();
});
}
}
Any idea what I did wrong here?
I already added Babel as suggested in this thread react export Unexpected token but the error didn't disappear.
I already tried to export it via modules.export, but no sucess either.
Thanks in advance!
EDIT:
Thats what my ".babelrc" looks like:
{
"presets": ["#babel/preset-react"],
"plugins": [
"babel-plugin-transform-export-extensions",
"transform-es2015-modules-commonjs"
]
}
Thats what my ".babelrc" looks like:
{
"presets": ["#babel/preset-react"],
"plugins": [
"babel-plugin-transform-export-extensions",
"transform-es2015-modules-commonjs"
]
}
This problem occurs because you are trying to use the same file as the service worker you are registering it with. Because of this, the browser cannot figure out which service worker features you need.
Use for example this content for service-worker.js in your public folder:
self.addEventListener('push', (event) => {
const data = event.data.json();
console.log('New notification', data);
event.waitUntil(
self.registration.showNotification(data.title, {
body: data.description,
icon: data.icon,
})
);
});
I am working on react native application. There I have to fetch user locations like multiple if user moves/navigates from one place to other. This is working fine, but, If user disables location permission after some time like user goes to settings there disabled permission, I have to show some button like enable location and again Once user tap on that button It should ask to Request Permission for location.
But, If user first time gives permission and later in some time if he disables permission, The popup for Request permission not showing popup in Android on tap of button.
I am using following library to fetch user location details.
import Geolocation from 'react-native-geolocation-service';
// button on click method following
enableLocationHandler = () => {
if (Platform.OS === 'android') {
this.requestLocationPermissions();
} else {
Linking.openURL('app-settings:');
this.getLatitudeLongitude();
}
}
requestLocationPermissions = async () => {
if (Platform.OS === 'android') {
this.getLatitudeLongitude();
} else {
Geolocation.requestAuthorization();
this.getLatitudeLongitude();
}
}
getLatitudeLongitude() {
Geolocation.getCurrentPosition((position) => {
const initialPosition = JSON.stringify(position);
},
(error) => {
if (error.code === 1) {
this.setState({ errorMessage: 'Location permission is denied', isLoading: false });
Geolocation.clearWatch(this.watchID);
}
},
{ enableHighAccuracy: true, distanceFilter: 100, timeout: 20000, maximumAge: 1000 }
);
this.watchID = Geolocation.watchPosition((position) => {
// this.showLoader();
// console.log('position', position);
});
}
Any suggestions?
IN this plugin react-native-geolocation-service, There is no declared run time permission in android. that's by in android , permission dialog is not showing .
To resolve this issue add this permission before request for fetch location
import {PermissionsAndroid} from 'react-native';
async function requestAccessLocationPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS. ACCESS_FINE_LOCATION,
{
title: 'Application wants location Permission',
message:
'Application wants location Permission',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
} else {
}
} catch (err) {
console.warn(err);
}
}
this will helps you, it helps me.
In my RN application, I have the following code.
import { PermissionsAndroid } from 'react-native';
export default new Promise(() => {
return PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.READ_CONTACTS, {
title: 'Contacts List',
message: 'Canvas would like to view your contacts',
});
});
What I want to do is, I want to return, if the promise is successful or not. Then, I can get the promised status and handle the android permissions according to that. But the current code returns this.
40
:
0
_55
:
null
_65
:
0
_72
:
null
__proto__
:
Object
What am I doing wrong here?
Because the function for the current authority is asynchronous, if the result is returned immediately, the value is returned before the result is obtained. Therefore, it is advisable to check the value after putting it in the variable. Or, it is desirable to receive the results after conversion in a synchronous fashion.
That object at the end looks like the value you want.
example (Use Async )
import {PermissionsAndroid} from 'react-native';
async function requestCameraPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: 'Cool Photo App Camera Permission',
message:
'Cool Photo App needs access to your camera ' +
'so you can take awesome pictures.',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log('You can use the camera');
} else {
console.log('Camera permission denied');
}
} catch (err) {
console.warn(err);
}
}
example (Use Sync )
import {PermissionsAndroid} from 'react-native';
function requestCameraPermission() {
try {
PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,
{
title: 'Cool Photo App Camera Permission',
message:
'Cool Photo App needs access to your camera ' +
'so you can take awesome pictures.',
buttonNeutral: 'Ask Me Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
).then(result => { console.log(result) }).catch(err => console.log(err));
} catch (err) {
console.warn(err);
}
}
const requestPermission = async (requestedType) => {
try {
return await PermissionsAndroid.requestMultiple(requestedType);
} catch (e) {
return e;
}
};
const permissionsRequired = [PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION];
const permissionResponse = yield call(requestPermission, permissionsRequired);
Try above code. Hope this help.
I want to access the phone camera roll photos, in React-native by this code:
_handleButtonPress = () => {
CameraRoll.getPhotos({
first: 20,
assetType: 'Photos',
})
.then(r => {
this.setState({ photos: r.edges });
})
.catch((err) => {
alert(err)
});
};
but i get this Error in alert:
could not get photos need: read_external_storage permission
As mentioned in the Google Docs, if the device is running Android 6.0 (API level 23) or higher, and the app's targetSdkVersion is 23 or higher, the user isn't notified of any app permissions at install time.
Therefore you must ask the user to grant the dangerous permissions at runtime
Here's a list of Dangerous Permissions.
You can enable the permissions in React Native as
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,
{
'title': 'Access Storage',
'message': 'Access Storage for the pictures'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can use read from the storage")
} else {
console.log("Storage permission denied")
}
} catch (err) {
console.warn(err)
}
Check here for more details
i added this code in AndroidManifest located at(( Example/android/app/src/main/AndroidManifest.xml)):
<uses-permission android:name="android.permission.CAMERA"/>
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
then i confirmed app permissions in android(and i dont know how to do it at run time) and problem solved.