I am currently working on an app using react native that requires location services to be on for some of its features. I have been researching if there is a simple way to test if the user has them turned on or not so I can display a different view if they aren't. I have not found any results other than ones that are specific to IOS or Android. Has anyone else found a solution to this?
Geolocation is enabled by default when you create a project with react-native init . In order to enable geolocation in the background, you need to include the 'NSLocationAlwaysUsageDescription' key in Info. plist and add location as a background mode in the 'Capabilities' tab in Xcode.
Geolocation in React Native In this React Native geolocation tutorial, we'll use the react-native-geolocation-service library, which is available as a Node package on npm. We'll build an app that does the following: Asks permission to access location data on your Android and iOS device. Picks your location coordinates.
Use the "react native android location services dialog box" module for android
https://www.npmjs.com/package/react-native-android-location-services-dialog-box
install
npm install react-native-android-location-services-dialog-box --save
js
import LocationServicesDialogBox from "react-native-android-location-services-dialog-box";
LocationServicesDialogBox.checkLocationServicesIsEnabled({
message: "Use Location ?",
ok: "YES",
cancel: "NO"
}).then(function(success) {
console.log(success); // success => "enabled"
).catch((error) => {
console.log(error.message); // error.message => "disabled"
});
Do a watchPosition or getCurrentPosition, Your second argument is a callback in case of failure, and its argument is the reason it failed.
So, from there you know when and why it fails. You'll need an if for the reason if you only want to act on 'location disabled' and not 'request timed out' for example.
You can use the callback to add a flag to your state for example.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With