What is the right way to access the the front or back camera.
Currently I'm only able to access the "user" camera ( front ).
I can't switch to back camera using any constraints.
Using a specific device id is also not working:
var constraints = {
video: {
facingMode: "environment",
deviceId: "E858F78F6026428D45DD669617B4A881409AA4DA"
}
};
navigator.mediaDevices.getUserMedia(constraints).
Cany somebody please help me?
It is always accessing the front camera.
Following your question I think you already have successfully called getUserMedia() to get the user's permission to access the camera (otherwise you won't have get the front camera to work). This is needed because the label values in the following JSON will only be filled when the user has already granted access.
On iOS you now have to call navigator.mediaDevices.enumerateDevices() and will get a "response JSON" like that:
[
{
"deviceId":"<firstID>",
"kind":"audioinput",
"label":"iPhone Microphone",
"groupId":""
},
{
"deviceId":"<secondID>",
"kind":"videoinput",
"label":"Back Camera",
"groupId":""
},
{
"deviceId":"<thirdID>",
"kind":"videoinput",
"label":"Front Camera",
"groupId":""
}
]
using the deviceId of the device you want or let the user choose it using a basic UI will give you access to the back camera.
Caution: The deviceId values will change on each invocation of enumerateDevices()!
You can also pass this in as an argument when you are calling getUserMedia.
video: {
facingMode: {
exact: 'environment'
}
}
This will return the back camera's video:
navigator.mediaDevices.getUserMedia({
video: {
facingMode: {
exact: 'environment'
}
}
})
Related
I am building an app using React Native and photo upload is one of its key functions. Here is what I am trying to do:
When the user clicks on the button to open the camera roll, tell whether the user allowed camera access or not.
If the user didn't allow, show an alert to ask the user to turn on the permission from settings to ensure proper experience on the app.
Where should I look at to start tackling this? I am new to programming in general and not familiar at all with native code. I know this is a high-level question so some high-level guidance will be appreciated. Thanks!
You can start at looking at react-native-permissions module. It allows you to ask for any kind of permissions that a mobile app can require, and also the dialogs are handled natively so you dont have to worry about building the alerts yourself.
https://github.com/zoontek/react-native-permissions
Here's an example on how to handle image selection with permissions
import ImagePicker, {
ImagePickerOptions,
ImagePickerResponse,
} from 'react-native-image-picker';
import { openSettings } from 'react-native-permissions';
import { alertWrapper } from './alert';
export const selectPicture = (options: ImagePickerOptions) => {
const pickerPromise = new Promise<ImagePickerResponse>((resolve) => {
try {
ImagePicker.showImagePicker(options, (response: ImagePickerResponse) => {
if (response.didCancel) {
return;
}
if (response.error) {
if (response.error.includes('permissions')) {
alertWrapper('Error', response.error, [
{ text: 'Open Settings', onPress: () => openSettings() },
]);
}
return;
}
resolve(response);
});
} catch (e) {
throw e;
}
});
return pickerPromise;
};
I'm using qr_code_scanner to scan barcodes in my Flutter app and it works fine for Android, but when I try to scan for iOS a pop-up appears and looks like:
I'm using the descriptions Flutter code that looks like the following:
QRView(
key: qrKey,
onQRViewCreated: (controller) => {
controller.scannedDataStream.listen((code) async {
...
})
})
And in my Info.plist file I have the following fields:
<key>io.flutter.embedded_views_preview</key>
<true/>
<key>NSCameraUsageDescription</key>
<string>Camera permission is required to scan QR codes.</string>
However even with these settings set, I can't seem to figure out how to have access to the camera. Thanks for any help.
Update
I followed #EvgeniyTrubilo suggestion and used permission_handler to request permission using the following code:
void getCameraPermission() async {
print(await Permission.camera.status); // prints PermissionStatus.granted
var status = await Permission.camera.status;
if (!status.isGranted) {
final result = await Permission.camera.request();
if (result.isGranted) {
setState(() {
canShowQRScanner = true;
});
} else {
Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Please enable camera to scan barcodes')));
Navigator.of(context).pop();
}
} else {
setState(() {
canShowQRScanner = true;
});
}
}
The first time this code was executed it successfully requested permission to access camera, and once permission was granted, the same error showed up. Sequential tries the print statement at the top of the above function said the Permission was granted??
Update 2x
Just realized you can mock the camera in an iOS simulator like you can on Android. I will try this on an actual device and update.
You can use permission_handler. With this, you could ask for camera permission before build QRView. Of course, you should build QRView after camera permission is enabled.
I'm not sure it would be right solution for your issue, but I think that would be an awesome improvement.
I have Xamarin.Android app which has a webview and asks permissions for camera and microphone. In my public override void OnPermissionRequest(PermissionRequest request), I want to check what is the permission requesting and show the relavant alert. But I don't know how to check whether its Camera permission or microphone. How can I check it?
Thanks!
Check the following code , PermissionRequest contains the request which the webview want to apply.
public override void OnPermissionRequest(PermissionRequest request)
{
base.OnPermissionRequest(request);
var resources = request.GetResources();
foreach ( var permission in resources)
{
if(permission == PermissionRequest.ResourceVideoCapture)
{
// apply camera permission
}
if(permission==PermissionRequest.ResourceAudioCapture)
{
// apply microphone permission
}
}
}
When the user is prompted for a permission on Safari, the video element is shown as a black rectangle with a strikethrough play button. How do I change this element's styling? Does it have a specific ID / class / tag?
I'm using Quagga JS as a barcode scanner. AFAIK Quagga creates a video element, then asks for camera permission. The optimal result would be to hide the element using display:none;, but I can't think of any way to accomplish this. I need the element to display the camera feed once the scanner has its permission, but before that it should either paint the screen black or be hidden.
I've fixed it by hiding it via JavaScript and showing it once the Quagga Feedback has finished. Note that a pure CSS solution would be much prettier.
// Hide the preview before it's fully initialised.
$('#videoBoundingBox').hide();
Quagga.init({
inputStream: {
name: "Live",
type: "LiveStream",
target: document.querySelector('#videoBoundingBox')
},
decoder: {
readers: [
"code_128_reader",
"ean_reader"
]
}
}, function (err) {
if (err) {
console.log(err);
setResult(err);
err = err.toString();
if (err.search("NotFoundError")) {
// No camera found. The user is probably in an office environment.
// Redirect to previous orders or show a background image of sorts.
} else if (err.search("NotAllowedError")) {
// The user has blocked the permission request.
// We should ask them again just to be sure or redirect them.
} else {
// Some other error.
}
return;
}
// Hide the preview before it's fully initialised.
$('#videoBoundingBox').show();
setResult("Initialization finished. Ready to start");
console.log("Initialization finished. Ready to start");
Quagga.start();
initializeQuaggaFeedback();
});
I have an application that requires a page refresh whenever the orientation changes (ipad/iphone). Within this application, HTML5 videos also gets presented at certain times in UX. Whenever a user is viewing a video in full screen mode, their first inclination is to rotate the device to landscape orientation if it was not already in that mode. When they do this, however, it triggers the nasty page reload, effectively ending their viewing session. By tapping into webkit full screen API I was able to write logic to control this behavior, which works perfectly on Safari desktop as well as with the iPad/iPhone user agent selected in developer tools, but it DOES NOT work on the native iphone/ipad.
document.webkitIsFullScreen returns false/true correctly in console in Safari, but comes up as undefined on iphone/ipad. Can anyone tell me how to accomplish this on ipad/iphone, since these are the only devices that require this functionality anyway? Or is there a much simpler solution that I am overlooking? Any help is greatly appreciated!
$(document).ready( function () {
var video = document.getElementById('video');
var canrefresh = true;
video.addEventListener("webkitfullscreenchange",function(){
// Detects if video is in full screen mode and toggles canrefresh variable
// canrefresh = false when webkitfullscreenchange event is heard
// canrefresh = true after exiting full screen
if (canrefresh == true) {
canrefresh = false;
} else {
canrefresh = true;
}
console.log(document.webkitIsFullScreen+' | '+canrefresh);
}, false);
$(window).resize(function() {
// Look to make sure not in full screen, and canrefresh variable is true before refreshing page
if((document.webkitIsFullScreen == false) && (canrefresh == true)){
window.location = window.location.href+'?v='+Math.floor(Math.random()*1000);
}
});
console.log(document.webkitIsFullScreen+' | '+canrefresh);
$('body .test').text(document.webkitIsFullScreen+' | '+canrefresh); // document.webkitIsFullScreen is returning 'false' in Safari (correct), but 'undefined' on native iphone/ipad device
});
The equivalent property which is compatible with Mobile Safari is the webkitDisplayingFullscreen property on the HTMLVideoElement DOM object.