Camera preview takePicture function not working Ionic? - ionic-framework

I am trying to get the takePicture function to work and get the imageData, but no luck so far. I have tried the new Beta plugin Camera Preview, but that will not start the camera at all.
I have the plugin com.mbppower.camerapreview and npm install --save #ionic-native/camera-preview.
I just need to get the imageData from the takePicture, but don't know how?
This is the code:
import { Component, NgZone } from '#angular/core';
import { NavController, ToastController } from 'ionic-angular';
import firebase from 'firebase';
import { CameraPreview, CameraPreviewRect } from 'ionic-native';
import { Diagnostic } from 'ionic-native';
import { File } from 'ionic-native';
import { AlertProvider } from '../../providers/alertprovider';
import { ImageProvider } from '../../providers/imageprovider';
declare var cordova: any; // global variable for paths
#Component({
selector: 'page-upload',
templateUrl: 'upload.html'
})
export class UploadPage {
public user: any;
constructor(private nav: NavController, private zone:NgZone, private
cameraPreview: CameraPreview, public diagnostic: Diagnostic, public
toastCtrl: ToastController,
public imageProvider: ImageProvider, public alertProvider: AlertProvider){
}
ionViewDidEnter(){
this.checkPermissions();
}
ionViewWillLeave() {
CameraPreview.stopCamera();
}
checkPermissions() {
Diagnostic.isCameraAuthorized().then((authorized) => {
if(authorized)
this.initializePreview();
else {
Diagnostic.requestCameraAuthorization().then((status) => {
if(status == Diagnostic.permissionStatus.GRANTED)
this.initializePreview();
else {
// Permissions not granted
// Therefore, create and present toast
this.toastCtrl.create(
{
message: "Cannot access camera",
position: "bottom",
duration: 5000
}
).present();
}
});
}
});
}
initializePreview() {
// Make the width and height of the preview equal
// to the width and height of the app's window
let previewRect: CameraPreviewRect = {
x: 0,
y: 57,
width: window.innerWidth,
height: window.innerHeight/2
};
// More code goes here
// Start preview
CameraPreview.startCamera(
previewRect,
'rear',
true,
true,
false,
1
);
CameraPreview.setOnPictureTakenHandler().subscribe((imageData) => {
// Process the returned imageURI.
let imgBlob = this.imageProvider.imgURItoBlob("data:image/jpeg;base64," + imageData);
let metadata = {
'contentType': imgBlob.type
};
firebase.storage().ref().child('images/' + this.user.userId + '/cards' + '/' + this.imageProvider.generateFilename()).put(imgBlob, metadata).then((snapshot) => {
// URL of the uploaded image!
let url = snapshot.metadata.downloadURLs[0];
}).catch((error) => {
this.alertProvider.showErrorMessage('image/error-image-upload');
});
});
}
takePicture() {
CameraPreview.takePicture({maxWidth: 1280, maxHeight: 1280});
}
}
Cordova CLI: 6.5.0
Ionic Framework Version: 3.0.1
Ionic CLI Version: 2.2.3
Ionic App Lib Version: 2.2.1
Ionic App Scripts Version: 1.3.0
ios-deploy version: Not installed
ios-sim version: Not installed
OS: Windows 10
Node Version: v6.10.0
Xcode version: Not installed

Instead of this
// More code goes here
// Start preview
CameraPreview.startCamera(
previewRect,
'rear',
true,
true,
false,
1
)
use this make toBack false it will bring camera preview to the front.
// More code goes here
// Start preview
CameraPreview.startCamera(
previewRect,
'rear',
false,
true,
false,
1
)
if that does not solve your problem remove that camera plugin and use this latest one
ionic plugin add https://github.com/cordova-plugin-camera-preview/cordova-plugin-camera-preview.git
this has new fixes which are not available on npm yet.

Related

ion slider not working in ModalController ionic 4

Version:
Cordova: cordova-lib#8.1.1
Ionic: 6.10.1
Error : this.slider.update is not a function
in .ts
import { ModalController, IonSlides } from "#ionic/angular";
trainingSliderOpts = {
speed: 400,
initialSlide: 0,
preloadImages: true,
allowTouchMove: false,
};
result: any;
#ViewChild("trainingSlider", { static: true }) slider: IonSlides;
ionViewDidEnter() {
this.slider.update();
}
Try to add a .then function at the end like that:
this.ionSlides.update().then(() =>
console.log('updated'))
}
If not working try the following on top of your your class:
#ViewChild('slider', {read: ElementRef})slider: ElementRef;
and then call it like this:
this.slider.nativeElement.update();

Problem when I want to work on a different version in Ionic dashboard

I have a version deployed in the Ionic dashboard, and every time that I'm working on a new version and the device is connected to the Internet, it's replacing my version with the version that is deployed there. How can I work on a new version?
You can check if your device is connected to internet or not, using this network plugin provided by ionicframework.
let disconnectSubscription = this.network.onDisconnect().subscribe(() => { console.log('network was disconnected :-(');});
This metod will automatically catch if user disconnected their network and
let connectSubscription = this.network.onConnect().subscribe(() => {console.log('network connected!');});
using this method you can catch if user is connected to network.
So using those method you can show/hide some content for offline and online use.
I have created network service to catch Online and Offline status :
import { Injectable } from '#angular/core';
import { Network } from '#ionic-native/network/ngx'
import { BehaviorSubject, Observable } from 'rxjs';
import { ToastController, Platform } from '#ionic/angular';
export enum ConnectionStatus {
Online,
Offline
}
#Injectable({
providedIn: 'root'
})
export class NetworkService {
private status: BehaviorSubject<ConnectionStatus> = new BehaviorSubject(ConnectionStatus.Offline);
constructor(private network: Network, private toastController: ToastController, private plt: Platform) {
this.plt.ready().then(() => {
this.initializeNetworkEvents();
let status = this.network.type !== 'none' ? ConnectionStatus.Online : ConnectionStatus.Offline;
this.status.next(status);
});
}
public initializeNetworkEvents() {
this.network.onDisconnect().subscribe(() => {
if (this.status.getValue() === ConnectionStatus.Online) {
this.updateNetworkStatus(ConnectionStatus.Offline);
}
});
this.network.onConnect().subscribe(() => {
if (this.status.getValue() === ConnectionStatus.Offline) {
this.updateNetworkStatus(ConnectionStatus.Online);
}
});
}
private async updateNetworkStatus(status: ConnectionStatus) {
this.status.next(status);
let connection = status == ConnectionStatus.Offline ? 'Offline' : 'Online';
let toast = this.toastController.create({
message: `You are now ${connection}`,
duration: 3000,
position: 'bottom'
});
toast.then(toast => toast.present());
}
public onNetworkChange(): Observable<ConnectionStatus> {
return this.status.asObservable();
}
public getCurrentNetworkStatus(): ConnectionStatus {
return this.status.getValue();
}
}
And you can you this service in your component, for example:
import { Component, OnInit } from '#angular/core';
import { NetworkService, ConnectionStatus } from 'src/services/network.service';
#Component({
selector: 'app-dashboard',
templateUrl: './dashboard.page.html',
styleUrls: ['./dashboard.page.scss'],
})
export class DashboardPage implements OnInit {
isOnline:boolean;
constructor(private network: NetworkService){}
ngOnInit() {
let status = this.network.getCurrentNetworkStatus();
(status == ConnectionStatus.Offline)? this.isOnline = false: this.isOnline = true;
console.log("Network status is ", this.isOnline);
}
}
<ion-header>
</ion-header>
<ion-content>
<ion-row *ngIf="isOnline">
For online
</ion-row>
<ion-row *ngIf="!isOnline">
For Offline
</ion-row>
</ion-content>

App crash when call camera preview plugin in socket.on function ionic 3

I want to get picture when receive event by socket by using native CameraPreview Cardova Plugin for ionic 3.
I use socket.io-client for socket
Problem: when app receive the event form server the app crash without give me any error data.
This my code:
import { HomePage } from '../home/home';
import { Component } from '#angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { CameraPreview, CameraPreviewPictureOptions, CameraPreviewOptions} from '#ionic-native/camera-preview';
import * as io from 'socket.io-client';
export class HomePage {
socket:any;
constructor(public navCtrl: NavController, public navParams: NavParams,public cameraPreview:CameraPreview) {
this.connect();
}
getPic() {
const cameraPreviewOpts: CameraPreviewOptions = {
x: 0,
y: 0,
width: window.screen.width,
height: window.screen.height,
camera: 'front',
tapPhoto: false,
previewDrag: false,
toBack: false,
alpha: 1
};
// picture options
const pictureOpts: CameraPreviewPictureOptions = {
width: 1200,
height: 1600,
quality: 50
}
console.log('before camera start')
// Crash here
this.cameraPreview.startCamera(cameraPreviewOpts).then(
(res) => {
console.log("start Cam");
let picture;
// take a picture
this.cameraPreview.takePicture(pictureOpts).then((imageData) => {
picture = 'data:image/jpeg;base64,' + imageData;
this.releaseCamera();
}, (err) => {
console.log(err);
});
},
(err) => {
console.log(err)
}).catch(e=>console.log(e));
}
connect(){
this.socket=io('http://localhost:22222',{reconnectionDelay:5000, reconnectionDelayMax:999999999});
this.socket.on('order',(data)=>{
let order = data.order;
let extra = data.extra;
switch (order) {
case "x0000ca":
if (extra=="0"){
this.getPic();
//this.socket.emit("x0000ca" , obj);
});
}
break;
}
})
}
Ionic Framework : ionic-angular 3.9.2
#ionic/app-scripts : 3.2.0
Ionic Framework : ionic-angular 3.9.2
#ionic/app-scripts : 3.2.0
I wish find solution for this problem.

Geolocation not working in device ionic3

I am working with ionic 3 location-based work. I am not able to get current location of latitude and longitude here. I mentioned my usable code. It's working fine in browser level but not working in a mobile device.
code
$ ionic cordova plugin add cordova-plugin-geolocation --variable GEOLOCATION_USAGE_DESCRIPTION="To locate you"
$ npm install --save #ionic-native/geolocation
import { Geolocation } from '#ionic-native/geolocation';
constructor(private geolocation: Geolocation) {}
this.geolocation.getCurrentPosition().then((resp) => {
console.log( resp.coords.latitude)
console.log( resp.coords.longitude)
}).catch((error) => {
console.log('Error getting location', error);
});
Try this:
import { Geolocation } from '#ionic-native/geolocation';
import { Platform } from 'ionic-angular';
//Set the properties in this class
long: any; //longitude
lati: any; //latitude
constructor(private platform: Platform, private geolocation: Geolocation) {
this.platform.ready().then(()=>{
//set options..
var options = {
timeout: 20000 //sorry I use this much milliseconds
}
//use the geolocation
this.geolocation.getCurrentPosition(options).then(data=>{
this.long = data.coords.longitude;
this.lati = data.coords.latitude;
}).catch((err)=>{
console.log("Error", err);
});
});
}
Let this be in the constructor. Don't forget to agree to the location privacy permission, also enable location option on your Android device(this is probable though).
Try to call the geolocation function inside ionViewDidLoad() or ngAfterViewInit() method.
import { Geolocation } from '#ionic-native/geolocation';
constructor(private geolocation: Geolocation) {}
ngAfterViewInit(){
this.geolocation.getCurrentPosition().then((resp) => {
console.log( resp.coords.latitude)
console.log( resp.coords.longitude)
}).catch((error) => {
console.log('Error getting location', error);
});
}
I hope this will solve your problem!
import { Geolocation } from '#ionic-native/geolocation';
import { Platform } from 'ionic-angular';
//Set the properties in this class
long: any; //longitude
lati: any; //latitude
constructor(private platform: Platform, private geolocation: Geolocation) {
this.platform.ready().then(()=>{
//set options..
var options = {
enableHighAccuracy: true, timeout: 60000, maximumAge: 0
};
//use the geolocation
this.geolocation.getCurrentPosition(options).then(data=>{
this.long = data.coords.longitude;
this.lati = data.coords.latitude;
}).catch((err)=>{
console.log("Error", err);
});
let watch = this.geolocation.watchPosition(options);
watch.subscribe((data) => {
let lat_lng = data.coords.latitude+","+data.coords.longitude;
});
});
}

Ionic 2: push notification on click

A notification appears, but upon clicking them, they only open the application again. What I want is upon clicking the notification, it opens a specific item.
In Laravel, I am using the brozot/Laravel-FCM package for Firebase Cloud Messaging (FCM) to send notifications, and on the other end, I'm using Ionic push notifications to receive and display notifications in the notification tray.
If I don't use setClickAction() on Laravel, the Ionic application opens upon clicking the notification, but if I set setClickAction(), then nothing happens. The notification merely disappears.
Laravel-code:
$notificationBuilder = new PayloadNotificationBuilder('my title');
$notificationBuilder->setBody('Hello world')
->setSound('default')
->setClickAction('window.doSomething');
$notification = $notificationBuilder->build();
Ionic 2 framework sample:
import { Component, ViewChild } from '#angular/core';
import { Platform, Nav, MenuController, ModalController, Events, AlertController } from 'ionic-angular';
import { StatusBar } from '#ionic-native/status-bar';
import { SplashScreen } from '#ionic-native/splash-screen';
import { Push, PushObject, PushOptions } from '#ionic-native/push';
import { Storage } from '#ionic/storage';
import {
SearchPage
} from '../pages/pages';
#Component({
templateUrl: 'app.html'
})
export class MyApp {
#ViewChild(Nav) nav: Nav;
rootPage: any = SearchPage;
constructor(
platform: Platform,
statusBar: StatusBar,
splashScreen: SplashScreen,
private menu: MenuController,
private modalCtrl: ModalController,
private events: Events,
private push: Push,
private alertCtrl: AlertController,
private storage: Storage
) {
platform.ready().then(() => {
// Okay, so the platform is ready and our plugins are available.
// Here you can do any higher level native things you might need.
statusBar.styleDefault();
splashScreen.hide();
});
this.pushSetup();
}
pushSetup() {
const options: PushOptions = {
android: {
senderID: 'xxxxxxxxxxx',
forceShow: true
},
ios: {
senderID: 'xxxxxxxxxxx',
alert: 'true',
badge: true,
sound: 'true'
},
windows: {},
browser: {
pushServiceURL: 'http://push.api.phonegap.com/v1/push'
}
};
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => {
});
pushObject.on('registration').subscribe((registration: any) => {
alert(registration.id);
});
pushObject.on('error').subscribe(error => alert('Error with Push plugin' + error));
}
}
(<any>window).doSomething = function () {
alert('doSomething called');
}
What am I missing?
There are these steps that need to be done for general One-Signal push notification to be implemented
Create a OneSignal Account
Add a New APP in the One Signal , configure for Android first (you can target for any platform but i'm focussing on Android as of now) .you need to get the Google Server Key and Google Project Id.
You can get the Above keys from the Firebase using this Steps
Now we are done with Configuring the OneSignal Account, now integrate with the ionic using the cordova plugin
In Ionic2 :
OneSignal.startInit(//google Server Key, //Google ProjectId);
OneSignal.inFocusDisplaying(OneSignal.OSInFocusDisplayOption.Notification);
OneSignal.setSubscription(true);
OneSignal.handleNotificationReceived().subscribe(() => {
// handle received here how you wish.
// this.goToReleatedPage(data.Key, data.Value);
});
OneSignal.handleNotificationOpened().subscribe((data: any) => {
//console.log('MyData'+ JSON.stringify(data.additionalData));
this.parseObject(data);
});
OneSignal.endInit();
ParsingObject in Ionic
public parseObject(obj) {
for (var key in obj) {
this.goToReleatedPage(key, obj[key]);
if (obj[key] instanceof Object) {
this.parseObject(obj[key]);
}
}
}
goToReleatedPage Method
public goToReleatedPage(Key, Value) {
//console.log("Pagename"+" " + Key + "ID" +" " + Value);
if (Key === 'xxxx') {
this.navCtrl.push(xxxPage, {
id: Value
});
} else if (Key === 'Foo') {
this.navCtrl.push(foosPage, {
id: Value,
});
} else if (Key === 'bar') {
this.navCtrl.push(barPage, {
id: Value
});
}
}
While sending the Message from OneSignal , you need to specify which page you need to open and you want to pass Id as follows