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;
}
}
}])
Related
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
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>
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)
}
I am really new to the mobile development world and trying my hands on it using IonicFramework.
I am creating a login form and on successful login the user gets take to another state which is called viewMyList. Everything seems to be working fine when I run the command ionic serve I am able to login and proceed to the next state and all seems to be fine on iOS simulator as well but on Android simulator on clicking the login button nothing happens, I don't see any error either.
My attempt
login.html
<ion-view title="Login">
<ion-content class="has-header" padding="true">
<form class="list">
<h2 id="login-heading3" style="color:#000000;text-align:center;">Welcome back!</h2>
<div class="spacer" style="width: 300px; height: 32px;"></div>
<ion-list>
<label class="item item-input">
<span class="input-label">Email</span>
<input type="text" placeholder="" ng-model="credentials.username">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="text" placeholder="" ng-model="credentials.password">
</label>
</ion-list>
<div class="spacer" style="width: 300px; height: 18px;"></div>
<a class="button button-positive button-block" ng-click="login()">Sign In</a>
</form>
</ion-content>
</ion-view>
ng-click is linked with login()
Here is my loginCtrl which contains the login() function
.controller('loginCtrl', function ($scope, $state, $ionicHistory, User) {
$scope.credentials = {
username: '',
password: ''
};
$scope.login = function () {
User.login($scope.credentials)
.then(function (response) {
console.log(JSON.stringify(response));
//Login should not keep any history
$ionicHistory.nextViewOptions({historyRoot: true});
$state.go('app.viewMyList');
})
};
$scope.message = "this is a message loginCtrl";
})
Here is my User service that takes care of the login logic
angular.module('app.user', [])
.factory('User', function ($http) {
var apiUrl = 'http://127.0.0.1:8000/api';
var loggedIn = false;
return {
login: function (credentials) {
console.log(JSON.stringify('inside login function'));
console.log(JSON.stringify(credentials));
return $http.post(apiUrl + '/tokens', credentials)
.success(function (response) {
console.log(JSON.stringify('inside .then of login function'));
var token = response.data.token;
console.log(JSON.stringify(token));
$http.defaults.headers.common.Authorization = 'Bearer ' + token;
persist(token);
})
.error(function (response) {
console.log('inside error of login function');
console.log(JSON.stringify(response));
})
;
},
isLoggedIn: function () {
if (localStorage.getItem("token") != null) {
return loggedIn = true;
}
}
};
function persist(token) {
window.localStorage['token'] = angular.toJson(token);
}
});
Here is the route behind the login
.state('login', {
url: '/login',
templateUrl: 'templates/login.html',
controller: 'loginCtrl'
})
I am really clueless at the moment as I cant seem to figure out why nothing happens on Android, from my troubleshooting all I could find was when I click on login button the code does not seem to be going inside the following function.
$scope.login = function () {
User.login($scope.credentials)
.then(function (response) {
console.log(JSON.stringify(response));
//Login should not keep any history
$ionicHistory.nextViewOptions({historyRoot: true});
$state.go('app.viewMyList');
})
};
Any help will really be appreciated.
Install whitelist plugin first.
cordova plugin add cordova-plugin-whitelist
add following code in your config.xml file under your root directory of project
<allow-navigation href="http://example.com/*" />
or:
<allow-navigation href="http://*/*" />
If still you are facing any issue, then you can check console while you are running in android device using chrome remote debugging
Connect your device with your machine.(Make sure USB debugging should be enable on your mobile).
write chrome://inspect in browser in your desktop chrome.
you will see connected device, select inspect and check console for log.
So I'm trying to get the camera to take a picture and display it in img tag, simple enough right ? Everything seems fine, I'm able to take a picture and the URI is printed, but I'm getting an error on $scope.$apply(). I'm running it on Android 4.4.4. Here's my code:
.controller("TakePictureController", function($scope, Camera) {
$scope.getPhoto = function() {
Camera.getPicture().then(function(imageURI) {
$scope.src = imageURI;
$scope.$apply();
console.log(imageURI);
}, function(err) {
console.log(err);
});
};
});
.factory('Camera', ['$q', function($q) {
return {
getPicture: function(options) {
var q = $q.defer();
navigator.camera.getPicture(function(result) {
q.resolve(result);
}, function(err) {
q.reject(err);
}, options);
return q.promise;
}
}
}])
and the HTML:
<ion-content class="padding">
<button class="button button-full button-positive" ng-click="getPhoto()">
Take pic
</button>
<img ng-src="{{src}}">
</ion-content>
This is what I get in the console as URI:
file:///storage/sdcard0/Android/data/com.ionicframework.overtredingbe668924/cache/1437826221441.jpg
This is the error I get:
12 237093 error Error: [$rootScope:inprog] $digest already in progress
http://errors.angularjs.org/1.3.13/$rootScope/inprog?p0=%24digest
I tried putting this in
if(!$scope.$$phase) {
$scope.$apply();
}
I don't get the error anymore, but picture is not shown. Any advice ?