File Chooser unsupported by cordova - android

I' m looking for a File chooser plugin for my ionic 5 app, but FileChooser is now unsupported by cordova. Are there other plugins that i can use. Thank you!

Does web API suit your needs instead of Cordova based approach?
it got decent support nowadays: https://caniuse.com/#search=FileReader
You could do it this way:
<ion-header>
<ion-toolbar>
<ion-title>
My super tabs app
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content>
<ion-card class="welcome-card">
<img [src]="imageUrl">
</ion-card>
<ion-button expand="full">
<ion-icon slot="start" name="image"></ion-icon>
<ion-label for="file-input">Choose file to upload</ion-label>
<input style="position: absolute; opacity: 0; width: 100%; height: 100%" type="file" (change)="loadImageFromDevice($event)" id="file-input" accept="image/png, image/jpeg">
</ion-button>
</ion-content>
Your ts:
import { Component } from '#angular/core';
import { DomSanitizer, SafeResourceUrl } from '#angular/platform-browser';
#Component({
selector: 'app-tab1',
templateUrl: 'tab1.page.html',
styleUrls: ['tab1.page.scss']
})
export class Tab1Page {
imageUrl: SafeResourceUrl;
dataUrl: string | ArrayBuffer;
constructor(private domSanitizer: DomSanitizer) {}
loadImageFromDevice = (event) => {
if (!event.target.files[0]) return;
const file = event.target.files[0];
if (!file.type.match('image')) return;
// do blob:
let blobReader = new FileReader();
blobReader.readAsArrayBuffer(file);
blobReader.onload = () => {
let blob: Blob = new Blob([new Uint8Array((blobReader.result as ArrayBuffer))]);
this.imageUrl = this.domSanitizer.bypassSecurityTrustResourceUrl(URL.createObjectURL(blob));
};
// do base64data:
/* let dataReader = new FileReader();
dataReader.readAsDataURL(file);
dataReader.onload = () => {
this.dataUrl = dataReader.result;
};
dataReader.onerror = (error) => {
console.log(error)
}; */
// handle errors:
blobReader.onerror = (error) => {
console.log(error)
};
};
}
This will leverage standard web API (input file) and recently all modern browsers / devies support this approach.
Definitely depends on your use case and for some it won't work.
Demo: https://stackblitz.com/edit/ionic-4-angular-8-start-template-ywc4r8

Related

How to get geolocation with Cordova Geolocation plugin from Android phone?

I am building an Android App with the Ionic Framework and I want to get the geolocation from my phone with Cordova Geolocation (https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-geolocation/).
While testing the implementation in the browser (ionic serve), everything seems to work fine. But when I try to test it on the phone (Samsung Galaxy S6) the location will not be shown.
Unfortunately I can not see any errors for debugging with ionic cordova run android.
Does anyone has an idea how to fix this?
tracking.page.ts
import { Component, OnInit } from '#angular/core';
import { Geolocation } from '#ionic-native/geolocation/ngx';
import * as moment from 'moment';
import { NativeGeocoder, NativeGeocoderOptions, NativeGeocoderResult } from '#ionic-native/native-geocoder/ngx';
#Component({
selector: 'app-tracking',
templateUrl: './tracking.page.html',
styleUrls: ['./tracking.page.scss'],
})
export class TrackingPage implements OnInit {
geoLatitude: number;
geoLongitude: number;
geoAccuracy: number;
watchLocationUpdates: any;
loading: any;
isWatching: boolean;
// Geocoder configuration
geoencoderOptions: NativeGeocoderOptions = {
useLocale: true,
maxResults: 5
};
constructor(
private geolocation: Geolocation,
private nativeGeocoder: NativeGeocoder
) { }
getMoment() {
return moment().milliseconds(0);
}
ngOnInit() {
document.addEventListener('deviceready', onDeviceReady, false);
function onDeviceReady() {
console.log('navigator.geolocation works well');
}
}
// Start location update watch
watchLocation() {
let options = {
maximumAge: 3600000,
timeout: 3000,
enableHighAccuracy: true,
}
this.isWatching = true;
this.watchLocationUpdates = this.geolocation.watchPosition();
this.watchLocationUpdates.subscribe((resp) => {
this.geoLatitude = resp.coords.latitude;
this.geoLongitude = resp.coords.longitude;
this.geoAccuracy = resp.coords.accuracy;
timestamp: this.getMoment().format('x');
// this.getGeoencoder(this.geoLatitude, this.geoLongitude);
});
}
// Stop location update watch
stopLocationWatch() {
this.isWatching = false;
console.log('this.isWatching = ', this.isWatching);
this.watchLocationUpdates.unsubscribe();
}
}
tracking.page.html
<ion-header>
<ion-toolbar color="primary">
<ion-title>
<div class="titleicon">
<div class="logo-img"><img src="../assets/logo.png" width="120px" /></div>
</div>
</ion-title>
</ion-toolbar>
</ion-header>
<ion-content class="ion-padding" style="text-align: center;">
<!-- *ngIf="geoLatitude" -->
<div>
Address: {{ geoAddress }}
</h1> -->
<h4>Latitude: {{geoLatitude}}</h4>
<h4>Longitude: {{geoLongitude}}</h4>
<p>Genauigkeit: {{geoAccuracy}} m</p>
</div>ยด
<ion-button (click)="watchLocation()">
Route starten
</ion-button>
<br>
<ion-button (click)="stopLocationWatch()" color="danger">
Route beenden
</ion-button>
</ion-content>

[Ionic]What is the best manner to retrieve images from firebase storage?

Like the title reflects, I found difficulties to display the images that I store on firebase. I saved before the paths in order to obtain the full url and push it into img tag. here my idea :
file.ts :
//imageList contains the url of each image
urlImages : Array<string> = [];
for(let img of this.imageList ) {
this.firestore.ref(img.url).getDownloadURL().then((url) => {
console.log("promise "+url);
this.urlImages.push(url);
});
}
And in file.html :
<ion-item-sliding *ngFor='let img of urlImages'>
<img [src]="img" />
</ion-item-sliding>
I'm beginner with ionic and angular env ...
So thanks in advance for your help.
Put those to iconic home page
<ion-header>
<ion-navbar>
<ion-title>Home</ion-title>
</ion-navbar>
</ion-header>
<ion-content padding>
<h2>Welcome to Ionic!</h2>
<ion-list>
<ion-item *ngFor="let item of imagelink">
<ion-thumbnail slot="start">
<img src= {{item}} >
</ion-thumbnail>
</ion-item>
</ion-list>
</ion-content>
2.add those files to home.ts file
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
groceries: any;
constructor(public navCtrl: NavController) {
this.imagelink= [
'https://www.gstatic.com/webp/gallery3/1.sm.png',
'https://www.gstatic.com/webp/gallery3/1.sm.png',
'https://www.gstatic.com/webp/gallery3/1.sm.png',
'https://www.gstatic.com/webp/gallery3/1.sm.png',
'https://www.gstatic.com/webp/gallery3/1.sm.png',
'https://www.gstatic.com/webp/gallery3/1.sm.png'
];
}
}

Ionic Native File Opener plugin won't open .pdf files with default app in Android

I'm quite new to the whole Ionic and Cordova environment and I'm having some trouble trying to open a .pdf file from the Ionic app with the default native pdf reader.
Here is my markup:
<ion-scroll overflow-scroll="true" scrollX="true">
<ion-card>
<ion-card-content>
<a href="assets/sheets/clicks_bs.pdf">
<img src="assets/sheets/clicks_bs.jpg"/>
</a>
</ion-card-content>
</ion-card>
<ion-card>
<ion-card-content>
<a href="assets/sheets/makro.pdf">
<img src="assets/sheets/makro.png" />
</a>
</ion-card-content>
</ion-card>
<ion-card>
<ion-card-content>
<a href="assets/sheets/picknpay_bs.pdf">
<img src="assets/sheets/picknpay_bs.jpg"/>
</a>
</ion-card-content>
</ion-card>
</ion-scroll>
Here is my component:
import { Component, ViewChild } from '#angular/core';
import { Slides } from 'ionic-angular';
import { FileOpener } from '#ionic-native/file-opener';
#Component({
selector: 'page-home',
templateUrl: 'home.html',
providers: [FileOpener]
})
export class HomePage {
#ViewChild('storebrands') slides: Slides;
constructor(private fileOpener: FileOpener ) {
let i = 0;
setInterval(() => {
this.goToSlide(i);
if (i === 8)
i = 0;
else
i++;
}, 5000);
this.fileOpener.open('assets/sheets/*.pdf', 'application/pdf')
.then(() => console.log('File is opened'))
.catch(e => console.log('Error openening file', e));
}
}
I have imported the file opener and injected it into the constructor and I've added it as a provider, however when I try clicking on the image in Android, it does nothing. Can someone please give some insight on why it isn't opening in the default .pdf reader on a native device.
Thanks in advance!
Use DocumentViewer Plugin
showDocument(pdff){
const options: DocumentViewerOptions = {
title: 'My PDF',
openWith: { enabled: true},
bookmarks : {
enabled : true
},
search : {
enabled : true
},
autoClose: {
onPause : true
}
}
const imgeLocation = `${cordova.file.applicationDirectory}www/assets/imgs/${pdff}`;
this.document.viewDocument(imgeLocation, 'application/pdf', options)
}

Cordova angular app wont switch views after several re-launches

The application runs fine on first launch, I can switch views and display ng-dialogues(i am using named ui-views),
After one or two suspensions or re-launches it still respond fine, and I can still scroll and type in inputs.
But it refuses to switch to other view or display an ng-dialogue. This issues goes away after force stopping the app.
I have tried to switch launch mode in config.xml to singleInstance and singleTask with no success. The problem is also present in release build.
Is doubt that my code causing this because it runs once right? Any idea?
Here is a sample code for the angular route main controller and index.html.
route
(function() {
"use strict";
angular
.module("cvideo")
.config(routeConfig);
/** #ngInject */
function routeConfig($stateProvider, $urlRouterProvider) {
$stateProvider
.state("home", {
url: "/",
views: {
nav: {
templateUrl: "app/components/navbar/navbar.html",
controller: "NavCtrl"
},
content: {
templateUrl: "app/main/main.html",
controller: "MainCtrl"
}
}
})
.state("jobs", {
url: "/jobs",
views: {
nav: {
templateUrl: "app/components/navbar/navbar.html",
controller: "NavCtrl"
},
content: {
templateUrl: "app/components/job/newJob.html",
controller: "JobCtrl"
}
}
});
$urlRouterProvider.otherwise("/");
}
})();
index.html
<body>
<div ui-view="nav"></div>
<div class="content" ui-view="content"></div>
</body>
MainCtrl
(function(){
"use strict";
angular.module("cvideo")
.controller("MainCtrl", function ($scope, ngDialog) {
$scope.jobs = [];
for (var i = 1; i < 10; i++) {
var job = {
title: "Job Offer " + Math.round(Math.random()*1000),
date: new Date(100*60 * 60 * 24 * 365*50*i),
description: "Job Offer "+i+" Description.",
qualification: "Job Offer " + i + " Required Qulifications.",
video: {
limit: i*10,
local: "",
web: ""
}
};
$scope.jobs.push(job);
}
$scope.preview = function (job) {
$scope.job = job;
ngDialog.open({
template: "app/components/job/job.html",
scope: $scope,
showClose:false
});
};
});
})();
main.html
<div class="jumbotron col-md-4" ng-repeat-start="job in jobs">
<div class="container">
<div class="row" ng-click="preview(job)">
<h3 ng-bind="job.title"></h3>
<label ng-bind="job.date|date:'Due MM/dd/yyyy'"></label>
<p ng-bind="job.description.length>100?job.description.substr(0,97)+'...':job.description"></p>
<div class="clearfix" ng-if="$index%3==2"></div>
</div>
</div>
</div>
<div ng-repeat-end=""></div>

ionic/cordova camera for a newbie with angularJS

I am trying to use the camera. I've searched for an example or a guide but I couldn't find anything.
What I want to do is to simply open the camera on the push of a button, get a picture, and display the image - all using ionic and angular.
Here is what i did
index.html:
<ion-nav-buttons side="left">
<button menu-toggle="left"class="button button-icon icon ion-navicon"></button>
</ion-nav-buttons>
<ion-content class="has-header contentPadding">
<div class="form-group padding-top">
<button class='button button-positive' data-ng-click="takePicture()">
{{text.buttonTitle}}
</button>
</div>
<div class="item item-image">
<img ng-src="{{cameraPic}}"/>
</div>
</ion-content>
The controller:
$scope.takePicture = function(){
var cameraOptions = {
quality: 50,
destinationType: Camera.DestinationType.DATA_URL
};
var success = function(data){
$scope.$apply(function () {
/*
remember to set the image ng-src in $apply,
i tried to set it from outside and it doesn't work.
*/
$scope.cameraPic = "data:image/jpeg;base64," + data;
});
};
var failure = function(message){
alert('Failed because: ' + message);
};
//call the cordova camera plugin to open the device's camera
navigator.camera.getPicture( success , failure , cameraOptions );
};
Perhaps this can help you: Ionic Cordova Example
Immediately available for Phonegap Build!
Thank you #AMG for posting a link to the Ionic Camera example project. I analyzed it and found that we need to inject Camera into the controller, like so:
.controller('MyCtrl', function($scope, Camera) {
Note that there is not a dollar sign before Camera. This really should be documented more explicitly.
Also, you need to add this factory:
.factory('Camera', ['$q', function($q) {
return {
getPicture: function(options) {
var q = $q.defer();
navigator.camera.getPicture(function(result) {
// Do any magic you need
q.resolve(result);
}, function(err) {
q.reject(err);
}, options);
return q.promise;
}
}
}])

Categories

Resources