I'm following this tutorial to get user's location on iOS React Native app:
https://hackernoon.com/react-native-basics-geolocation-adf3c0d10112
Using this code to get current location:
navigator.geolocation.getCurrentPosition((position) => {
console.log(position); // TBD
this.setState({ location: true });
}, (error) => {
console.log(error); // Handle this
this.setState({ location: false });
}, {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 1000,
});
But the app crashes at this file:
PermissionsAndroid.js:
const shouldShowRationale = await NativeModules.PermissionsAndroid.shouldShowRequestPermissionRationale(
with error:
TypeError: Cannot read property shouldShowRequestPermissionRationale of undefined at PermissionsAndroid.Request$
But I'm not even running on Android - I'm running iOS.
Could this be a RN bug or how I'm using it?
Just had to request permissions first:
await navigator.geolocation.requestAuthorization();
Related
Please provide the following:
SDK Version: "^42.0.0",
Platforms(Android/iOS/web/all): iOS
Add the appropriate "Tag" based on what Expo library you have a question on.
Hello,
[expo-notifications] Error encountered while updating server registration with latest device push token., [Error: Another async call to this method is in progress. Await the first Promise.]
This error often occurs in expo app. And always occurs in build ios app.
Using the following code:
async function registerForPushNotificationsAsync() {
let token
if (Constants.isDevice) {
const { status: existingStatus } = await Notifications.getPermissionsAsync()
let finalStatus = existingStatus
if (existingStatus !== 'granted') {
const { status } = await Notifications.requestPermissionsAsync({
ios: {
allowAlert: true,
allowBadge: true,
allowSound: true,
allowAnnouncements: true,
},
})
finalStatus = status
}
if (finalStatus !== 'granted') {
console.log('noti cancel')
return
}
// token = (await Notifications.getExpoPushTokenAsync()).data
try {
await Notifications.getExpoPushTokenAsync().then((res) => {
console.log('getExpoPUshTokenAsync >> ', res)
token = res.data
})
} catch (err) {
console.log('getExpoPushTokenAsync error >> ', err)
}
} else {
Alert.alert(
'Must use physical device for Push Notifications'
)
}
if (Platform.OS === 'android') {
Notifications.setNotificationChannelAsync('default', {
name: 'default',
importance: Notifications.AndroidImportance.MAX,
vibrationPattern: [0, 250, 250, 250],
lightColor: '#FF231F7C',
})
}
return token
}
I have received a new credential, but I am still getting the error.
I used Geolocation in my react native code to get the current position and it is working well on Android. But not work on iOS.
Here is my code
import Geolocation from "#react-native-community/geolocation";
import Geocoder from "react-native-geocoder";
_getCurrentLocation = () => {
Alert.alert(
"Get Location",
"Do you want to update your location?",
[
{
text: 'Cancel',
onPress: () => console.log('Cancel Pressed'),
style: 'cancel'
},
{
text: 'UPDATE', onPress: () => {
Geolocation.setRNConfiguration({ skipPermissionRequests: true, authorizationLevel: "always" });
if (Platform.OS === 'ios') Geolocation.requestAuthorization();
Geolocation.getCurrentPosition(
info => {
const position = { lat: info.coords.latitude, lng: info.coords.longitude }
Geocoder.geocodePosition(position).then(res => {
console.warn(res);
const { updateUserState } = this.props;
updateUserState({ position : position, country : res[0].countryCode, city : res[0].adminArea });
this.setState({ position : position, country : res[0].countryCode, city : res[0].adminArea });
})
.catch(err => {
console.warn(err)
alert(JSON.stringify(err));
})
},
error => {
// alert("Sorry, we cann't get your location now, please check your permission!")
alert(JSON.stringify(error));
console.log(error)
},
{
enableHighAccuracy: false,
timeout: 3000,
// maximumAge: 1000,
},
)
}
}
],
{ cancelable: false }
)
}
I am getting the below error:
PERMISSION_DENIED: 1
POSITION_UNAVAILABLE: 2
TIMEOUT: 3
code: 3
message: "Unable to fetch location within 15.0s."
This is my info.plist:
<key>NSLocationAlwaysUsageDescription</key>
<string>This app requires access to you location.</string>
<key>NSLocationWhenInUseUsageDescription</key>
<string>This app requires access to you location.</string>
please set custom latlong in the emulator, Debug -> Location -> Custom
Location and set custom latitude and longitude and run the app agin
Question
I have been trying to figure out why this is not working for some time. I have used a lot of example code, however I still cannot figure it out.
Code
takeVideo() {
console.log('started to take video');
this.camera.capture({
audio: true,
mode: Camera.constants.CaptureMode.video,
target: Camera.constants.CaptureTarget.disk
}).then((data) => {
this.setState({ path: data.path });
console.log(data);
}).catch((err) => console.log(err));
}
stopVideo() {
this.camera.stopCapture();
console.log(this.state.path);
}
renderCamera() {
return (
<View>
<Camera
ref={(cam) => {
this.camera = cam;
}}
style={styles.preview}
aspect={Camera.constants.Aspect.fill}
captureTarget={Camera.constants.CaptureTarget.disk}
captureMode={Camera.constants.CaptureMode.video}
>
<TouchableHighlight
style={styles.capture}
onPressIn={this.takeVideo.bind(this)}
onPressOut={this.stopVideo.bind(this)}
underlayColor="rgba(255, 255, 255, 0.5)"
>
<View />
</TouchableHighlight>
</Camera>
</View>
);
}
Whats not working
When I console.log(this.state.path) it outputs false which means that it does not change and the video did not record.
Info
This is on IOS
This works if I change Camera.constants.CaptureMode.video to Camera.constants.CaptureMode.still (.video => .still)
RN version:
react-native-cli: 2.0.1
react-native: 0.44.0
Repo
I found this repo that is trying to do almost the exact same thing as me and is having the same issue. Here is the repo: https://github.com/MiLeung/record
Everything in your code is ok, however you're missing one important thing.
this.camera.capture({
audio: true,
mode: Camera.constants.CaptureMode.video,
target: Camera.constants.CaptureTarget.disk
}).then((data) => {
this.setState({ path: data.path });
console.log(data);
}).catch((err) => console.log(err));
In code above, you're telling state, to set object path after saving the data.
But, there:
stopVideo() {
this.camera.stopCapture();
console.log(this.state.path);
}
You're fetching path object before saving the data.
Just try this:
this.camera.capture({
audio: true,
mode: Camera.constants.CaptureMode.video,
target: Camera.constants.CaptureTarget.disk
}).then((data) => {
this.setState({ path: data.path });
console.log(this.state.path); // You should have your path set
console.log(data);
}).catch((err) => console.log(err));
stopCapture function tells the native code, to stop recording and save video - what can take some time, so executing this.state.path immediately after stopCapture does not work.
For more info check this out https://developer.mozilla.org/pl/docs/Web/JavaScript/Reference/Global_Objects/Promise
I am able to create pdf in my ionic app and if I run the app in chrome it opens perfectly. However if I install my app on the android device it doesn't open. Below is my code. Can someone please help me if I have to do something extra to open it on device. I want to open it with default pdf application on device.
pdfMake.createPdf(dd).open();
Ok. After banging my head on wall for 3 days I finally found the solution and sharing here so that other people who are facing this issue can get help. I am creating pdf and saving it using cordova file plugin. After successful save I am opening it in default application using cordova file opener plugin. Below is my code.
pdfMake.createPdf(YOUR_DEFINITION_HERE).getBlob(buffer => {
this.file.resolveDirectoryUrl(this.file.externalRootDirectory)
.then(dirEntry => {
this.file.getFile(dirEntry, 'test1.pdf', { create: true })
.then(fileEntry => {
fileEntry.createWriter(writer => {
writer.onwrite = () => {
this.fileOpener.open(fileEntry.toURL(), 'application/pdf')
.then(res => { })
.catch(err => {
const alert = this.alertCtrl.create({ message:
err.message, buttons: ['Ok'] });
alert.present();
});
}
writer.write(buffer);
})
})
.catch(err => {
const alert = this.alertCtrl.create({ message: err, buttons: ['Ok'] });
alert.present();
});
})
.catch(err => {
const alert = this.alertCtrl.create({ message: err, buttons: ['Ok']
});
alert.present();
});
});
I'm currently trying to implement some functionality in my react native app where I use information stored locally if the device is offline, and perform a fetch if the device is online.
I used NetInfo after reading this How to handle network failure in React-Native, when network is off, but unfortunately I ran into an error where NetInfo always returns offline. I found this github issue, which recommended that I change the host in RCTReachability.m from 'htpp://apple.com' to 'apple.com'. However, I couldn't find a file with that name in the project directory. Instead I found the only mention of 'apple.com' in any file, which was in RCTNetInfo.m, which was in the correct form.
Does anybody know a way to fix this problem? Or possibly a different way to go about performing one action if the device is online, and another if the device is offline?
Here's the relevant code:
fetchData() {
NetInfo.isConnected.fetch().done((isConnected) => {
console.log('First, is ' + (isConnected ? 'online' : 'offline'));
if ( isConnected )
{
fetch(REQUEST_URL)
.then((response) => response.json())
.then((responseData) => {
store.save('contacts', responseData.feed.entry)
.then(() => store.get('contacts'))
.then((contacts) => {
this.setState({
dataSource: this.state.dataSource.cloneWithRows(contacts),
isLoading: false
});
})
})
.catch((error) => { console.error(error); });
}
else
{
store.get('contacts')
.then(contacts => {
if (contacts == null)
{
this.setState({
dataSource: this.state.dataSource.cloneWithRows(CONTACT_DATA),
isLoading: false
});
}
else
{
this.setState({
dataSource: this.state.dataSource.cloneWithRows(contacts),
isLoading: false
});
}
})
}
});
}