Ionic cordova-plugin-qrscanner has no camera preview - cordova-plugins

I run a simple demo to use cordova-plugin-qrscanner, it can scan qrcode but no camera preview.
qrscannerDemo on Github
Related code blow:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { AndroidPermissions } from '#ionic-native/android-permissions';
import { QRScanner, QRScannerStatus } from '#ionic-native/qr-scanner';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,
public androidPermissions: AndroidPermissions,
public qrScanner: QRScanner) {
}
qrscanner() {
// Optionally request the permission early
this.qrScanner.prepare()
.then((status: QRScannerStatus) => {
if (status.authorized) {
// camera permission was granted
alert('authorized');
// start scanning
let scanSub = this.qrScanner.scan().subscribe((text: string) => {
console.log('Scanned something', text);
alert(text);
this.qrScanner.hide(); // hide camera preview
scanSub.unsubscribe(); // stop scanning
});
this.qrScanner.resumePreview();
// show camera preview
this.qrScanner.show();
// wait for user to scan something, then the observable callback will be called
} else if (status.denied) {
alert('denied');
// camera permission was permanently denied
// you must use QRScanner.openSettings() method to guide the user to the settings page
// then they can grant the permission from there
} else {
// permission was denied, but not permanently. You can ask for permission again at a later time.
alert('else');
}
})
.catch((e: any) => {
alert('Error is' + e);
});
}
}
<ion-header>
<ion-navbar transparent>
<ion-title>
Ionic Blank
</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding style="background: none transparent;">
<button ion-button (click)="qrscanner()">qrscanner</button>
</ion-content>
I run the ionic project on android then click the button but nothing happened and no camera preview show.
I test the project again and find it can scan qrcode and get the result test, but no camera preview.
I search the problem, someone says should to set the body and any elements transparent. I try but does not work.
Android. Nothing appears on screen. #35
AnyOne help?

In top level index.html:
<ion-app style="background: none transparent;"></ion-app>
In camera display page html file:
<ion-content style="background: none transparent;">

After some research even i found the answer and surely this works fantastic for all ,but #nokeieng answer helped me too..
1) First, make a new component for qrscanner. In ionic there is a lifecycle in ionic so go according to that after entering the component this event trigger ionViewDidEnter().In this event the camera opens and let you scan.
ionViewDidEnter(){
this.qrScanner.prepare()
.then((status: QRScannerStatus) => {
if (status.authorized) {
// camera permission was granted
var camtoast = this.toastCtrl.create({
message: 'camera permission granted',
duration: 1000
});
camtoast.present();
// start scanning
this.qrScanner.show()
window.document.querySelector('ion-app').classList.add('cameraView');
let scanSub = this.qrScanner.scan().subscribe((text: string) => {
console.log('Scanned something', text);
window.document.querySelector('ion-app').classList.remove('cameraView');
this.qrScanner.hide(); // hide camera preview
const toast = this.toastCtrl.create({
message: 'You scanned text is this :'+text,
duration: 6000
});
toast.present();
scanSub.unsubscribe(); // stop scanning
});
} else if (status.denied) {
const toast = this.toastCtrl.create({
message: 'camera permission was denied',
duration: 3000
});
toast.present();
// camera permission was permanently denied
// you must use QRScanner.openSettings() method to guide the user to the settings page
// then they can grant the permission from there
} else {
const toast = this.toastCtrl.create({
message: 'You can ask for permission again at a later time.',
duration: 3000
});
toast.present();
// permission was denied, but not permanently. You can ask for permission again at a later time.
}
})
.catch((e: any) => console.log('Error is', e));
}
2) After this remove the camera class when back button is pressed for that add this code.
ionViewWillLeave() will triggers when component is destroyed or left.
ionViewWillLeave(){
window.document.querySelector('ion-app').classList.remove('cameraView');
}
3) We are done with .ts file. Now we have to make the component and the main element i.e ion-app transparent so that we can see the camera for that we add this css inside theme/variables.scss
ion-app.cameraView ion-nav{opacity:0}
and
ion-app.cameraView,ion-app.cameraView ion-content,ion-app.cameraView .nav-decor,{
background: transparent url("../../assets/imgs/camera_overlay.png") !important;
background-size: 100% 100% !important;}
4) As you can see I have given a background image so that we get a camera overlay preview
and you are done with the code just run this command in terminal to see live changes in ionic
ionic cordova run android --livereload

You just need to toggle the ion-app display between "none" and "block" if the status is authorized.
const ionApp = <HTMLElement>document.getElementsByTagName("ion-app")[0];
// start scanning
const scanSub = this.qrScanner.scan().subscribe((link: string) => {
ionApp.style.display = "block";
this.qrScanner.hide(); // hide camera preview
scanSub.unsubscribe(); // stop scanning
});
ionApp.style.display = "none";
this.qrScanner.show();

There is a div, with class=“nav-decor”, which has a black background, this needs to be changed to transparent.
I changed 3 things to transparent for the camera to show: ion-app, ion-content and .nav-decor
My solution was to have a “cameraView” class, which would set the ion-app, ion-content and .nav-decor to have a transparent background.
I used this CSS
ion-app.cameraView, ion-app.cameraView ion-content, ion-app.cameraView .nav-decor {
background: transparent none !important;
}
And then these functions to show the camera after qrScanner.show() and hide it after I’m finished scanning
showCamera() {
(window.document.querySelector('ion-app') as HTMLElement).classList.add('cameraView');
}
hideCamera() {
(window.document.querySelector('ion-app') as HTMLElement).classList.remove('cameraView');
}

I've work around following many answers,
Here is my solution combined all of the answer I've read.
In my scss file named page-scan.scss
page-scan {}
ion-app.cameraView,
ion-app.cameraView ion-content,
ion-app.cameraView .nav-decor,
ion-header,
ion-navbar,
ion-title {
background: transparent none !important;
}
ion-app.cameraView {
background-size: 100% 100% !important;
/* To show image border */
background-image: url([YOU CAN USE BASE64 image here!!]) !important;
}
Note: image border like this one
Here is the sample image:
file scan.html
<ion-header>
<ion-navbar color="primary_dark">
<ion-title>scan</ion-title>
</ion-navbar>
</ion-header>
<ion-content>
</ion-content>
file scan.ts. add these functions to show and hide camera preview
private showCamera() {
((<any>window).document.querySelector('ion-app') as HTMLElement).classList.add('cameraView');
}
private hideCamera() {
((<any>window).document.querySelector('ion-app') as HTMLElement).classList.remove('cameraView');
}
And finally, call show, scan and preview camera like code below
this.showCamera();
this.qrScanner.show()
this.subScan = this.qrScanner.scan()
See issue on github here

Update your cordova-android.
I fixed this when updated to cordova android 10.1.0
cordova platform remove android
cordova platform add android#10.1.0

.ion-page{display:none important!}

Related

Get Permission to Scan Barcodes on iOS with Flutter

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.

How to show a video from gallery in Ionic iOS

I am using html5's video tag to show a video I select from the gallery. I'm getting an issue where the video doesn't load even though I've provided a source.
This is an Ionic/Angular project with Capacitor as the bridge, but still using Cordova plugins. Here is a prototype of my code:
my-page.page.ts
import { Camera, CameraOptions } from '#ionic-native/camera/ngx';
import { Capacitor } from '#capacitor/core';
#Component({...})
export class MyPage {
// ... some code which gets the a reference to the video element from the template
// this function is called when the user clicks a button to choose video from gallery
onPickVideo() {
const cameraOptions: CameraOptions = {
destinationType: this.camera.DestinationType.NATIVE_URI,
sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM,
mediaType: this.camera.MediaType.VIDEO,
};
this.camera.getPicture(cameraOptions).then(videoUri => {
console.log(videoUri);
this.videoSrc = Capacitor.convertFileSrc(videoUri);
console.log(this.videoSrc);
this.videoEl.load();
this.videoEl.currentTime = 0.1;
});
}
}
my-page.page.html
<video playsinline #video>
<source [src]=".videoSrc" type="video/mp4" />
Your browser does not support the video tag.
</video>
The output of my-page.page.ts is:
file:///private/var/mobile/Containers/Data/Application/7D85727C-CE9A-4816-BC42-C97F03AFDEB4/tmp/F6DCE819-ED4A-41E4-BAFB-814500F2FB27.MOV
capacitor://localhost/_capacitor_file_/private/var/mobile/Containers/Data/Application/7D85727C-CE9A-4816-BC42-C97F03AFDEB4/tmp/F6DCE819-ED4A-41E4-BAFB-814500F2FB27.MOV
This works on desktop and on Android. It's not working on iPhone 6 with iOS 12. Untested on other iOS versions.
Some things I've tried:
Added NSCameraUsageDescription, NSPhotoLibraryUsageDescription, NSPhotoLibraryAddUsageDescription, NSMicrophoneUsageDescription
Used [src]= in the video tag, and removed the source tag. Or omitting the 'video/mp4' type
Running in live reload mode vs just building.
Chopping 'file:///' off the start of videoUri before passing it to convertFileSrc(). Or doing the former and directly setting it to videoSrc without using convertFileSrc() at all.
Solved by "sanitizing" the URL. I'm yet to learn what that really means. Here is the code in case anyone needs it
import { Camera, CameraOptions } from '#ionic-native/camera/ngx';
import { Capacitor } from '#capacitor/core';
import { DomSanitizer, SafeUrl } from '#angular/platform-browser';
#Component({...})
export class MyPage {
// ... some code which gets the a reference to the video element from the template
safeUrl: SafeUrl;
constructor(private sanitizer: DomSanitizer) {}
// this function is called when the user clicks a button to choose video from gallery
onPickVideo() {
const cameraOptions: CameraOptions = {
destinationType: this.camera.DestinationType.NATIVE_URI,
sourceType: this.camera.PictureSourceType.SAVEDPHOTOALBUM,
mediaType: this.camera.MediaType.VIDEO,
};
this.camera.getPicture(cameraOptions).then(videoUri => {
this.safeUrl = this.sanitizer.bypassSecurityTrustUrl(
Capacitor.convertFileSrc(videoUri)
);
this.videoEl.load();
this.videoEl.currentTime = 0.1;
});
}
}
Then make sure to be using safeUrl in the template [src]="safeUrl".

Ionic4 camera plugin - cordova not avaliable on device?

I am working on an Ionic4 app which needs to be able to take a photo.
I added "cordova-plugin-camera". When i run a function of this plugin on real DEVICE to take photo, i get an error "cordova_not_avaliable".
(Note that OTHER native cordova plugins work just fine - even in same page / module).
I followed basic installation process on Ionic documentation for "cordova-plugin-camera". No other errors are thrown.
import { Component, OnInit } from '#angular/core';
import { Camera, CameraOptions } from '#ionic-native/camera/ngx';
#Component({
selector: 'app-picture',
templateUrl: './picture.page.html',
styleUrls: ['./picture.page.scss'],
})
export class PicturePage implements OnInit {
options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
constructor(private camera: Camera) { }
ngOnInit() {}
takePicture() {
this.camera.getPicture(this.options).then((imageData) => {
let base64Image = 'data:image/jpeg;base64,' + imageData;
// this.presentAlert('success');
}, (err) => {
// this.presentAlert(err); // Displays "cordova_not_avaliable"
// (For show on DEVICE. I know rest logic of alert is missing)
});
}
}
I would expect that cordova IS avaliable since it is running on an android Device. No other error is present (Also note that I get an exact same result on ionic serve).
Edit: "Also note i am not very experienced yet in this environments so i might be missing something obvious."
Edit: "title (removed preview)"
Found solution, In my camera options I was missing a
sourceType: this.camera.PictureSourceType.CAMERA
That solved the problem.

Style the default "No video source" / "No video permissions" black rectangle

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();
});

Phonegap: BarcodeScanner & Childbrowser plugins

I'm facing a problem using this 2 PhoneGap plugins: "BarcodeScanner" & "ChildBrowser" (inside an iOS app, with XCode 4 & PhoneGap 2.0).
I've a button "Scan" on my app UI. When the user clic on this button, the barcode scanner is launched.
So, in the Success function of the barcode scanner callback, I need to open the recovered URL from the scan in a new Childbrowser window (inner the app).
But the new Childbrowser window is never been opened, while the console displays "Opening Url : http://fr.wikipedia.org/" (for example).
Here is my JS part of code:
$("#btnStartScan").click(function() {
var scanBarcode = window.plugins.barcodeScanner.scan(
function(result) {
if (!result.cancelled){
openUrl(result.text);
}
},
function(error) {
navigator.notification.alert("scanning failed: " + error);
});
});
function openUrl(url)
{
try {
var root = this;
var cb = window.plugins.childBrowser;
if(cb != null) {
cb.showWebPage(url);
}
else{
alert("childbrowser is null");
}
}
catch (err) {
alert(err);
}
}
And all works fine if I call my openURL() function inside a Confirm alert callback for example, like this:
if (!result.cancelled){
navigator.notification.confirm("Confirm?",
function (b) {
if (b === 1) {
openUrl(result.text);
}
},
'Test',
'Yes, No');
}
But I need to launch the ChildBrowser window directly after a scan, without any confirm alert etc.
Does anybody know how to solve this please?
I also have this same problem.
Solve it by set timeout.
var scanBarcode = window.plugins.barcodeScanner.scan(
function(result) {
if (!result.cancelled){
setTimeout(function(){ openUrl(result.text); },500);
}
},
function(error) {
navigator.notification.alert("scanning failed: " + error);
});
I'm running into the exact same problem.
My application also has another mechanism to show a webpage besides the barcode reader and when I do that action I can see that the barcode-related page HAD loaded, but it never was shown.
In ChildBrowserViewController.m, I'm looking at the last line of loadURL() which is webView.hidden = NO; and I'm thinking that the child browser is set visible after we barcode but something about the barcode reader window caused the child browser to get set to the wrong z-order, but I'm not familiar enough with the sdk to know how to test that or try to bring it to the front.
Hope this helps target a potential area.

Resources