I commented that I am developing an application in IONIC 3 and I am working with the native file transfer library.
At the moment of wanting to download a file in IOS it does not execute it, not so when it is installed or debugged in android.
According to the ionic documentation I am implementing it correctly and I do not understand why or what is missing so that IOS can execute the transfer.download which is the instruction that is not executed
and I get the following error in the console:
console.warn: 'Native: tried accessing the FileTransfer plugin but it's not installed.
Below I leave my code:
import { FileTransfer, FileTransferObject } from '#ionic-native/file-transfer';
import { File } from '#ionic-native/file';
import { LoadingController } from 'ionic-angular';
declare var cordova: any;
#IonicPage()
#Component({
selector: 'page-liquidaciones',
templateUrl: 'liquidaciones.html',
})
export class LiquidacionesPage {
formLiquidaciones: FormGroup;
public txtCorreoLiquidacion;
rutUsuario: any;
resultado: any;
liquidaciones: any;
liquidacionesSeleccionadas:any={};
loading: any;
storageDirectory: string = '';
//private fileTransfer: FileTransferObject;
//private localPath = '';
constructor(public navCtrl: NavController,
public navParams: NavParams,
private alertCtrl: AlertController,
public formBuilder: FormBuilder,
public kiberKiberpro: KibernumKiberproProvider,
public databaseService: DatabaseServiceProvider,
private transfer: FileTransfer,
private file: File,
private androidPermissions: AndroidPermissions,
public loadingController: LoadingController,
public platform: Platform
){
this.formLiquidaciones = this.formBuilder.group({
txtCorreoLiquidacion: ['', Validators.required]
});
this.platform.ready().then(() => {
if(!this.platform.is('cordova')) {
return false;
}
if (this.platform.is('ios')) {
//this.storageDirectory = this.file.dataDirectory;
this.storageDirectory = cordova.file.dataDirectory;
}
else if(this.platform.is('android')) {
this.storageDirectory = cordova.file.externalRootDirectory + '/Download/';
this.androidPermissions.checkPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE).then(
result => {
if (result.hasPermission) {
// code
} else {
this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE).then(result => {
if (result.hasPermission) {
// code
}
});
}
},
err => this.androidPermissions.requestPermission(this.androidPermissions.PERMISSION.READ_EXTERNAL_STORAGE)
);
}
else {
return false;
}
});
this.databaseService.getSesion(2).then(result => {
this.rutUsuario = result.valor;
})
.catch( error => {
});
}
DescargarLiquidaciones(){
this.loading = this.loadingController.create({ content: "Descargando Liquidacion(es)..." });
const fileTransfer: FileTransferObject = this.transfer.create();
var enviarLiquidaciones = [];
for(var i in this.liquidacionesSeleccionadas) {
if(this.liquidacionesSeleccionadas[i]) {
enviarLiquidaciones.push(i);
}
}
if(enviarLiquidaciones.length == 0)
{
this.alerta("Debe seleccionar por lo menos una liquidación para que sea descargada.");
}
else
{
this.loading.present();
this.txtCorreoLiquidacion = '';
this.kiberKiberpro.DescargarEnviarLiquidaciones(this.rutUsuario,enviarLiquidaciones, this.txtCorreoLiquidacion).then((res) => {
this.resultado = res;
var respuesta = JSON.parse(this.resultado.data);
let datos: string = JWT(this.resultado.data);
if(respuesta.status == "200") {
let autorizacion = this.resultado.headers;
let nombreArchivo = datos.split("tmp/");
let urlFinal = datos;
fileTransfer.download(urlFinal , this.storageDirectory + nombreArchivo[1]).then((entry) => {
console.log("LLEGA ACA");
this.alerta("Se ha descargado el archivo de manera satisfactoria.");
console.log("LLEGA ACA 2");
this.loading.dismissAll();
console.log("LLEGA ACA 3");
this.databaseService.GuardaSQLlite(1, autorizacion.authorization);
this.navCtrl.setRoot(HomePage);
}, (error) => {
this.alerta("Hubo un error al momento de descargar el archivo. Si el problema persiste favor contactarse al 816 35 12 o 816 35 09.");
this.loading.dismissAll();
});
}
else if (respuesta.status == "201"){
this.alerta("Hubo un problema con el envío de la(s) liquidacion(es) al correo ingresado. Si el problema persiste favor contactarse al 816 35 12 o 816 35 09");
this.loading.dismissAll();
let autorizacion = this.resultado.headers;
this.databaseService.GuardaSQLlite(1, autorizacion.authorization);
}
else if (respuesta.status == "401"){
this.alerta("Token no válido.");
this.loading.dismissAll();
}
else{
this.alerta("Hubo un problema inesperado, Favor intente nuevamente. Si el problema persiste favor contactarse al 816 35 12 o 816 35 09");
this.loading.dismissAll();
}
}, (err) => {
this.alerta("Ha ocurrido un problema, intente nuevamente por favor. Si el error persiste pongase en contacto con el area de soporte.");
this.loading.dismissAll();
});
}
}
I remain attentive to your answers and I thank you in advance for your help and opinions
I forgot to put the information of my ionic which is the following:
Ionic:
ionic (Ionic CLI) : 4.1.2 (/usr/local/lib/node_modules/ionic)
Ionic Framework : ionic-angular 3.9.2
#ionic/app-scripts : 3.1.10
Cordova:
cordova (Cordova CLI) : 8.1.1 (cordova-lib#8.1.0)
Cordova Platforms : ios 4.5.4
Cordova Plugins : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 1.2.1, (and 6 other plugins)
System:
ios-deploy : 2.0.0
NodeJS : v8.12.0 (/usr/local/bin/node)
npm : 6.4.1
OS : macOS
Xcode : Xcode 9.4 Build version 9F1027a
It looks to me like your file transfer logic is not wrapped in a this.platform.ready() call. Could it be that there are times when this is called before platform ready (and thus, before the plugin is ready to be used)?
Related
I'm trying to load a pdf from the assets folder in ionic or to download one. I've watched some tutorials but all of them are giving me the same error.
Ionic:
ionic (Ionic CLI) : 4.1.2 (C:\Users\hanna\node_modules\ionic)
Ionic Framework : ionic-angular 3.9.3
#ionic/app-scripts : 3.2.1
Cordova:
cordova (Cordova CLI) : 8.1.2 (cordova-lib#8.1.1)
Cordova Platforms : android 6.4.0, browser 5.0.4
Cordova Plugins : cordova-plugin-ionic-keyboard 2.1.3, cordova-plugin-ionic-webview 3.1.2, (and 7 other plugins)
System:
NodeJS : v9.4.0 (C:\Program Files\nodejs\node.exe)
npm : 5.6.0
OS : Windows 10
The code :
import { Component } from '#angular/core';
import { DocumentViewer, DocumentViewerOptions } from '#ionic-
native/document-viewer/ngx';
import { FileOpener } from '#ionic-native/file-opener/ngx';
import { FileTransfer } from '#ionic-native/file-transfer/ngx';
import { File } from '#ionic-native/File/ngx';
import { NavController, Platform } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(
public navCtrl: NavController,
private file: File,
private ft: FileTransfer,
private document: DocumentViewer,
public platform: Platform
) {}
openLocalPdf() {
// let filePath = this.file.applicationDirectory + 'www/assets';
// if (this.platform.is('android') || this.platform.is('browser')) {
// let fakeName = Date.now();
// this.file.copyFile(filePath, 'Typescript_Jumpstart_Book_Udemy.pdf', this.file.dataDirectory, `${fakeName}.pdf`).then(result => {
// this.fileOpener.open(result.nativeURL, 'application/pdf')
// .then(() => console.log('File is opened'))
// .catch(e => console.log('Error opening file', e));
// })
// } else {
// // Use Document viewer for iOS for a better UI
// const options: DocumentViewerOptions = {
// title: 'My PDF'
// }
// this.document.viewDocument(`${filePath}/5-tools.pdf`, 'application/pdf', options);
// }
console.log('Documents Pressed.....');
const options: DocumentViewerOptions = {
title: "My PDF"
}
this.document.viewDocument('assets/Typescript_Jumpstart_Book_Udemy.pdf', 'application/pdf', options)
console.log('Documents Pressed..... afterrr');
}
downloadAndOpenPdf() {
let path = null;
if (this.platform.is('ios')) {
path = this.file.documentsDirectory;
} else {
path = this.file.dataDirectory;
}
const transfer = this.ft.create();
transfer.download('https://devdactic.com/html/5-simple-hacks-LBT.pdf', path + 'MyFile.pdf').then(entry => {
let url = entry.toURL();
this.document.viewDocument(url, 'application/pdf', {});
// this.fileOpener.open(url, 'application/pdf')
// .then(() => console.log('File is opened'))
// .catch(e => console.log('Error opening file', e));
});
}
}
the Error is :
ERROR TypeError: Object(...) is not a function
at DocumentViewer.viewDocument (index.js:29)
at HomePage.webpackJsonp.193.HomePage.openLocalPdf (home.ts:43)
at Object.eval [as handleEvent] (HomePage.html:10)
at handleEvent (core.js:13589)
at callWithDebugContext (core.js:15098)
at Object.debugHandleEvent [as handleEvent] (core.js:14685)
at dispatchEvent (core.js:10004)
at core.js:10629
at HTMLButtonElement.<anonymous> (platform-browser.js:2628)
at t.invokeTask (polyfills.js:3)
You are on Ionic 3, and you are using plugin version supported for Ionic 4. Use the plugins supported for Ionic 3 by going through Ionic v3 document.
Reference: https://ionicframework.com/docs/v3/native/
Step 1
Un-install all your native plugins.
Step 2
Install version 4. Example below
$ ionic cordova plugin add cordova-plugin-document-viewer
$ npm install --save #ionic-native/document-viewer#4
Step 3
Don't append ngx at the end of the import, it's only for Angular 6.
import { DocumentViewer } from '#ionic-native/document-viewer';
Step 4:
Repeat Step 2 and 3 for your other native plugins.
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.
I have implemented the push notification functionality in my ionic app but it is not working. I am not getting the register id after the app is deployed. Following is my code.
app.component.ts
constructor(public platform: Platform, public splashScreen: SplashScreen, public menu: MenuController,
private storage: StorageService,private toast: ToastService, public events: Events, private push: Push,
private alertCtrl: AlertController, public network: Network, private api: UserService) {
platform.ready().then(() => {
debugger
this.pushSetup();
this.userDetails = this.storage.getData('userDetails');
this.isAlertShown = false;
// this.task = setInterval(() => {
// this.checkInternet();
// }, 3000);
if (this.userDetails != undefined || this.userDetails != null) {
this.rootPage = 'welcome';
} else {
this.rootPage = 'login';
}
this.initializeApp();
});
pushSetup() {
console.log("inside pushSetup");
const options: PushOptions = {
android: {
senderID: '592660866764',
forceShow: 'true'
},
ios: {
alert: 'true',
badge: true,
sound: 'false'
}
};
console.log("inside pushSetup 1");
const pushObject: PushObject = this.push.init(options);
pushObject.on('notification').subscribe((notification: any) => console.log('Received a notification', notification));
pushObject.on('registration').subscribe((registration: any) =>console.log('Received a notification', registration));
pushObject.on('error').subscribe(error => console.error('Error with Push plugin', error));
}
Install the Cordova and Ionic Native plugins:
ionic cordova plugin add onesignal-cordova-plugin
npm install --save #ionic-native/onesignal
insert in app.module.ts Onesignal
import { OneSignal } from '#ionic-native/onesignal';
providers: [
....
OneSignal
...
]
In App Component you needs One Signal App ID and Google Project ID
in app.component.ts:
import { OneSignal } from '#ionic-native/onesignal';
import { Platform } from 'ionic-angular';
constructor(public oneSignal: OneSignal,
private platform: Platform) { }
onseSignalAppId: string = 'YOUR_ONESIGNAL_APP_ID';
googleProjectId: string = 'YOUR_GOOGLE_PROJECT_ID';
if(this.platform.is('cordova')) {
if (this.platform.is('android')) {
this.oneSignal.startInit(this.onseSignalAppId, this.googleProjectId);
}
else if (this.platform.is('ios')) {
this.oneSignal.startInit(this.onseSignalAppId);
}
this.oneSignal.inFocusDisplaying(this.oneSignal.OSInFocusDisplayOption.Notification);
this.oneSignal.handleNotificationReceived().subscribe(() => {
// do something when notification is received
});
this.oneSignal.handleNotificationOpened().subscribe(result => {
// do something when a notification is opened
});
this.oneSignal.endInit();
// AND THIS METHOD RETURN YOUR DEVICES USER_ID
this.oneSignal.getIds().then(identity => {
alert(identity.pushToken + ' it's PUSHTOKEN');
alert(identity.userId + 'it's USERID);
});
}
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;
});
});
}
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.