I need to add image picker in my app. I've created small class for image picker logic:
import {launchImageLibrary, launchCamera} from 'react-native-image-picker';
export default class ImagePickerService {
static openPickerLibrary(
setImageUrl: Dispatch<SetStateAction<string | null | undefined>>,
setModalVisible: Dispatch<SetStateAction<boolean>>,
) {
launchImageLibrary(
{mediaType: 'photo', includeBase64: true},
(response: any) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
setImageUrl(`data:image/jpeg;base64,${response.base64}`);
setModalVisible(false);
}
},
);
}
static openPickerCamera(
setImageUrl: Dispatch<SetStateAction<string | null | undefined>>,
setModalVisible: Dispatch<SetStateAction<boolean>>,
) {
launchCamera({mediaType: 'photo', includeBase64: true}, (response: any) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else {
setImageUrl(`data:image/jpeg;base64,${response.base64}`);
setModalVisible(false);
}
});
}
}
Then I call these methods this way:
<ModalButton
label="Take photo"
onPress={() =>
ImagePickerService.openPickerCamera(setImageUrl, setPickerVisible)
}
/>
<ModalButton
label="Choose photo"
onPress={() =>
ImagePickerService.openPickerLibrary(setImageUrl, setPickerVisible)
}
/>
Picker library works great. But picker camera doesn't open. Only the modal window closes and nothing else. Also there aren't any errors in console.
I don't understand why this happens. I have all permissions in AndroidManifest. Also I have tried this string and it didn't help:
android:requestLegacyExternalStorage="true"
Also I have tried these features and they also didn't help:
<uses-feature android:name="android.hardware.camera" android:required="false" />
<uses-feature android:name="android.hardware.camera.front" android:required="false" />
How can I fix this problem?
I solved my problem with react-native-camera.
Related
I used for the first time react-native-ble-manager.
The app has all the permissions, however when I run the BleManager.scan() the app is closing without any error or logs.
I know the code is a little ugly but it's just for testing, the first second I run the bluetooth manager start and after 5 seconds I run the scan.
But the crash happen immediately after 5 seconds.
Any idea why?
import BleManager from 'react-native-ble-manager';
const BleManagerModule = NativeModules.BleManager;
const bleManagerEmitter = new NativeEventEmitter(BleManagerModule);
const handleDiscoverPeripheral = (peripheral) => {
console.log('Got ble peripheral', peripheral);
if (!peripheral.name) {
peripheral.name = 'NO NAME';
}
peripherals.set(peripheral.id, peripheral);
setList(Array.from(peripherals.values()));
}
const handleStopScan = () => {
console.log('Scan is stopped');
}
let interval;
let gImageShow = true;
let gTime = 0;
BleManager.enableBluetooth()
.then(() => {
// Success code
console.log("The bluetooth is already enabled or the user confirm");
})
.catch((error) => {
// Failure code
console.log("The user refuse to enable bluetooth");
});
function App(props) {
const [shouldShow, setShouldShow] = useState(gImageShow);
useEffect(() => {
interval = setInterval(() => {
if (gTime == 1)
{
BleManager.start({showAlert: true});
bleManagerEmitter.addListener('BleManagerDiscoverPeripheral', handleDiscoverPeripheral);
bleManagerEmitter.addListener('BleManagerStopScan', handleStopScan );
PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION).then((result) => {
if (result) {
console.log("Permission is OK");
}
});
}
if (gTime == 5)
{
BleManager.scan([], 10, true);
}
gImageShow = !gImageShow;
setShouldShow(gImageShow);
gTime = gTime + 1;
},1000);
return () => clearInterval(interval);
}, []);
useEffect(() => {
});
the manifest is like:
xmlns:tools="http://schemas.android.com/tools"
package="com.diagnostic_ble">
<uses-permission android:name="android.permission.INTERNET" />
<uses-permission android:name="android.permission.BLUETOOTH" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.BLUETOOTH_ADMIN" android:maxSdkVersion="30" />
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" android:maxSdkVersion="28"/>
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" tools:targetApi="Q"/>
<!-- Needed only if your app looks for Bluetooth devices. -->
<uses-permission android:name="android.permission.BLUETOOTH_SCAN" />
<uses-permission-sdk-23 android:name="android.permission.ACCESS_BACKGROUND_LOCATION" />
<uses-permission android:name="android.permission.BLUETOOTH_ADVERTISE" />
The problem has been solved. The new android 12 (I think from this one), needs a different permission that it hasn't been updated in react-native-ble-manager webpage.
In the manifest you need to add
<uses-permission android:name="android.permission.BLUETOOTH_CONNECT" />
<uses-feature android:name="android.hardware.bluetooth_le" android:required="true"/>
Also, In the app.js you need to call once requestPermissions();
that it can be like
const requestPermissions = async () => {
if (Platform.OS === 'android') {
const apiLevel = await DeviceInfo.getApiLevel();
if (apiLevel < 31) {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
title: 'Location Permission',
message: 'Bluetooth Low Energy requires Location',
buttonNeutral: 'Ask Later',
buttonNegative: 'Cancel',
buttonPositive: 'OK',
},
);
} else {
const result = await requestMultiple([
PERMISSIONS.ANDROID.BLUETOOTH_SCAN,
PERMISSIONS.ANDROID.BLUETOOTH_CONNECT,
PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
]);
const isGranted =
result['android.permission.BLUETOOTH_CONNECT'] ===
PermissionsAndroid.RESULTS.GRANTED &&
result['android.permission.BLUETOOTH_SCAN'] ===
PermissionsAndroid.RESULTS.GRANTED &&
result['android.permission.ACCESS_FINE_LOCATION'] ===
PermissionsAndroid.RESULTS.GRANTED;
}
} else {
}
};
I am using image picker in react native but an error occurs:
file:///storage/emulated exposed beyond app through clipdata.item
On ios, the camera opens normally. and in android i can pick an image from gallery normally.
My code:
const selectFile = (itemI,inputValue) => {
let options = {
title: 'Select Image',
maxWidth:800,
maxHeight:800,
quality:0.2,
storageOptions: {
skipBackup: true,
path: 'images',
},
includeBase64: true,
saveToPhotos:true
};
ImagePicker.showImagePicker(options, (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.error) {
console.log('ImagePicker Error: ', response.error);
} else if (response.customButton) {
console.log(
'User tapped custom button: ',
response.customButton
);
alert(response.customButton);
} else {
//let source = response;
// You can also display the image using data:
let source = {
uri: 'data:image/jpeg;base64,' + response.data
};
filePath[itemI]=source;
addItemCustom(" ");
}
});
};
I tried to add:
<uses-feature android:name="android.hardware.camera.any" />
<uses-feature android:name="android.hardware.camera.autofocus" />
<uses-permission android:name="android.permission.CAMERA"/>
<uses-feature android:name="android.hardware.camera" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<application
....
android:requestLegacyExternalStorage="true"
...>
but the error is the same.
The react native android permission pop-up is not showing, I cannot download a file. It works on a simulator but not on a real phone.
Here is my permission function :
const requestAndroidStoragePermission = async () => {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,
{
title: "File access",
message:
"The app needs files access to download your performance.",
}
);
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
this.setState({ storagePermission: true });
this.setState({ showExportModal: true });
} else {
console.log("Files permission denied");
}
} catch (err) {
console.warn(err);
}
};
I have the permission on my AndroidManifest.xml :
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"
android:targetSdkVersion="29" />
Someone have an idea ?
On my expo ejected project, im trying to use expo-contacts with no success.
"react-native": "~0.61.5",
"expo": "~37.0.3",
i ran expo install expo-contacts
import * as Permissions from 'expo-permissions';
import * as Contacts from 'expo-contacts';
getContact = async () => {
try {
let { status } = await Permissions.askAsync(Permissions.CONTACTS);
if (status === 'granted') {
const { data } = await Contacts.getContactsAsync({
fields: [Contacts.Fields.Emails],
});
console.log("getContact / data: ", data);
if (data.length > 0) {
const contact = data[0];
console.log("getContact / contact: ", contact);
}
}
} catch(e){
console.log("getContact / error: ", e)
}
}
<TouchableOpacity style={{ marginTop: 20 }} onPress={() => this.getContact()}>
<Image source={contactsIcon} style={{ width: 30, height: 30 }} />
</TouchableOpacity>
Have you set up the permissions in your AndroidManifest.xml as follows:
<uses-permission android:name="android.permission.READ_CONTACTS" />
<uses-permission android:name="android.permission.WRITE_CONTACTS" />
Also take a note that: "For bare React Native projects, you must ensure that you have installed and configured the react-native-unimodules [1] package before continuing."
[1] https://github.com/expo/expo/tree/master/packages/react-native-unimodules
I have been trying to use React Native 's GeoLocalisation for an Android App. The poorly documentated module is found here https://facebook.github.io/react-native/docs/geolocation.html.
According to the documentation, you handle location permissions on Android using the following code in the AndroidManifest.xml file
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
However, my online research suggests that the above line of code is useless for versions of ANDROID >= 6.0
As my implementation of GeoLocation is not currently working, I have no other reason but to believe that location permissions are not correctly handled.
How do I successfully request location permission at run-time for React Native Android App?
I solved it by changing the targetSdkVersion ( same to compileSdkVersion, in my case 23) in android/app/build.gradle.
Edit AndroidManifest.xml located in android/src/main and add the
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
next :
import { PermissionsAndroid } from 'react-native';
and then add this method:
export async function requestLocationPermission()
{
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Example App',
'message': 'Example App access to your location '
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
console.log("You can use the location")
alert("You can use the location");
} else {
console.log("location permission denied")
alert("Location permission denied");
}
} catch (err) {
console.warn(err)
}
}
and access the method when you request the location at run-time
async componentWillMount() {
await requestLocationPermission()
}
This did not work for me
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
}
I referred to https://facebook.github.io/react-native/docs/permissionsandroid.html#request
and check() return a boolean
const granted = await PermissionsAndroid.check( PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION );
if (granted) {
console.log( "You can use the ACCESS_FINE_LOCATION" )
}
else {
console.log( "ACCESS_FINE_LOCATION permission denied" )
}
You could use the react native PermissionsAndroid to request the permission: https://facebook.github.io/react-native/docs/permissionsandroid.html#request
Or, an easier option will be using a library that does it for you, such as https://github.com/yonahforst/react-native-permissions
I've noticed two things:
You have to change compileSdkVersion 23 in build.gradle file
You have to add your View's click listener to display to Permission dialog.
Sample code:
import React, { Component } from 'react';
import { Text, PermissionsAndroid, Alert } from 'react-native';
export default class RuntimePermissionSample extends React.Component {
constructor(props) {
super(props);
}
async requestLocationPermission() {
const chckLocationPermission = PermissionsAndroid.check(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION);
if (chckLocationPermission === PermissionsAndroid.RESULTS.GRANTED) {
alert("You've access for the location");
} else {
try {
const granted = await PermissionsAndroid.request(PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION,
{
'title': 'Cool Location App required Location permission',
'message': 'We required Location permission in order to get device location ' +
'Please grant us.'
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
alert("You've access for the location");
} else {
alert("You don't have access for the location");
}
} catch (err) {
alert(err)
}
}
};
render() {
return (
<Text
onPress={() => this.requestLocationPermission()}>
Request Location Permission
</Text>
)
}
}
Hope this would help you.
You can ask location permission using following code
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.ACCESS_FINE_LOCATION
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
alert("You can use the location")
} else {
alert("Location permission denied")
}
} catch (err) {
console.warn(err)
}
alert('hi');
in Manifest
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
<uses-permission android:name="android.permission.CAMERA"/>
more details
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);
}
}
export default class AlertDetails extends Component{
async componentDidMount() {
await request_storage_runtime_permission()
}
}