I have created the basic ionic app which can launch camera. I installed all the required plugins and also i have used the right version of cordova . I am not getting any errors and also able to create apk for that . When using in apk in the android mobile, camera is not getting launched.
this is the home.html code adding camera module
<button ion-button (click)="takePhoto()">camera</button>
<p align="center"><img src="{{ myphoto }}"></p>
this is the home.ts file
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { Camera, CameraOptions } from '#ionic-native/camera';
import { Database } from '../../providers/database/database';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
tabBarElement: any;
splash = true;
myphoto:any;
public hasTrees : boolean = false;
public trees : any;
constructor(public navCtrl: NavController, private camera:Camera,
public DB : Database) {
this.tabBarElement = document.querySelector('.tabbar');
}
takePhoto(){
const options: CameraOptions = {
quality: 70,
destinationType: this.camera.DestinationType.DATA_URL,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}
this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
this.myphoto = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
ionViewDidLoad() {
this.tabBarElement.style.display = 'none';
setTimeout(() => {
this.splash = false;
this.tabBarElement.style.display = 'flex';
}, 4000);
}
ionViewWillEnter()
{
this.displayTrees();
}
displayTrees()
{
this.DB.retrieveTrees().then((data)=>
{
let existingData = Object.keys(data).length;
if(existingData !== 0)
{
this.hasTrees = true;
this.trees = data;
}
else
{
console.log("we get nada!");
}
});
}
addSpecies()
{
this.navCtrl.push('Add');
}
viewSpecies(param)
{
this.navCtrl.push('Add', param);
}
}
Related
I am currently creating a page that allows users to take pictures of both their identity card and selfie of themselves, however, i am not able to get the files from the file system to upload it using submitpicture().
Here is my typescript code:
import { Component, OnInit } from '#angular/core';
import { File } from '#ionic-native/file/ngx';
import { Camera, CameraOptions } from '#ionic-native/camera/ngx';
import * as firebase from 'firebase';
import { EmailComposer } from '#ionic-native/email-composer/ngx';
import { ModalController } from '#ionic/angular';
#Component({
selector: 'app-verifyidentity',
templateUrl: './verifyidentity.page.html',
styleUrls: ['./verifyidentity.page.scss'],
})
export class VerifyidentityPage implements OnInit {
constructor(public camera: Camera, public file: File, private modalController: ModalController, public emailComposer: EmailComposer) { }
nric: any;
selfie: any;
nricimageData: any;
selfieimageData: any;
ngOnInit() {
}
takenric() {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true,
cameraDirection: 1
}
this.camera.getPicture().then((imageData) => {
this.nricimageData = imageData
let filename = imageData.substring(imageData.lastIndexOf('/') + 1);
let path = imageData.substring(0, imageData.lastIndexOf('/') + 1);
this.file.readAsDataURL(path,filename).then((base64data) => {
this.nric = base64data;
firebase.storage().ref().child("test").put(imageData).then(snapshot => {
console.log('Uploaded image ');
});
})
});
}
takeselfie() {
const options: CameraOptions = {
quality: 100,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE,
saveToPhotoAlbum: true,
cameraDirection: 1
}
this.camera.getPicture().then((imageData) => {
this.selfieimageData = imageData
let filename = imageData.substring(imageData.lastIndexOf('/') + 1);
let path = imageData.substring(0, imageData.lastIndexOf('/') + 1);
this.file.readAsDataURL(path,filename).then((base64data) => {
this.selfie = base64data;
firebase.storage().ref().child("test").put(imageData).then(snapshot => {
console.log('Uploaded image ');
});
})
});
}
submitpicture() {
firebase.storage().ref().child("nric").put(this.nric); // this does not work!
}
I was wondering if it is possible to get the image from the android system with the file path and store it in a variable before uploading to firebase storage with submitpicture().
So sorry for any inconvenience caused and thank you.
Best regards,
Dan
I have been trying to insert a share button for a post in my app that is able to use the default apps installed in the android phone and can not seem to find a way through.
This is how my post.ts file looks like
import { Component } from '#angular/core';
import { NavParams, NavController, AlertController } from 'ionic-angular';
.
.
import { SocialSharing } from '#ionic-native/social-sharing';
/**
* Generated class for the PostPage page.
*/
#Component({
selector: 'page-post',
templateUrl: 'post.html'
})
export class PostPage {
post: any;
user: string;
comments: Array<any> = new Array<any>();
categories: Array<any> = new Array<any>();
morePagesAvailable: boolean = true;
constructor(
public navParams: NavParams,
public navCtrl: NavController,
public alertCtrl: AlertController,
private socialSharing: SocialSharing
) {
}
ionViewWillEnter(){
this.morePagesAvailable = true;
this.post = this.navParams.get('item');
Observable.forkJoin(
this.getAuthorData(),
this.getCategories(),
this.getComments())
.subscribe(data => {
this.user = data[0].name;
this.categories = data[1];
this.comments = data[2];
});
}
getAuthorData(){
return this.wordpressService.getAuthor(this.post.author);
}
getCategories(){
return this.wordpressService.getPostCategories(this.post);
}
getComments(){
return this.wordpressService.getComments(this.post.id);
}
loadMoreComments(infiniteScroll) {
let page = (this.comments.length/10) + 1;
this.wordpressService.getComments(this.post.id, page)
.subscribe(data => {
for(let item of data){
this.comments.push(item);
}
infiniteScroll.complete();
}, err => {
console.log(err);
this.morePagesAvailable = false;
})
}
goToCategoryPosts(categoryId, categoryTitle){
this.navCtrl.push(HomePage, {
id: categoryId,
title: categoryTitle
})
}
// Social sharing function is here
sharePost() {
this.socialSharing.share("Post Excerpt", "Post Title", "Post Image URL", "Post URL")
.then(() => {
console.log("sharePost: Success");
}).catch(() => {
console.error("sharePost: failed");
});
}
}
Problem
How do insert the post title, post url post image (REST API - JSON) into this.socialSharing.share("Post Excerpt", "Post Title", "Post Image URL", "Post URL")
so that the share button can look more like this
<button ion-fab class="btn share" mini (click)="sharePost()"></button>
EDIT
I have managed to make it work using
sharePost() {
this.socialSharing.share(this.post.excerpt.rendered, this.post.title.rendered, this.post.images.large, this.post.link)
.then(() => {
console.log("sharePost: Success");
}).catch(() => {
console.error("sharePost: failed");
});
}
However when i share like using gmail, the html special characters display
e.g title shows: catering & Cleaning Services
Excerpt shows: <p>Some text[…]</p>
How do i get rid of those html characters and just show some clean text.?
Thank you
One way i removed html tag from my wordpress post was to create a pipe and i pass the excerpt through the pipe before it gets rendered to the view
Pipe.ts was like so
import { Pipe, PipeTransform } from '#angular/core';
/**
* Generated class for the RemovehtmltagsPipe pipe.
*
* See https://angular.io/api/core/Pipe for more info on Angular Pipes.
*/
#Pipe({
name: 'RemovehtmltagsPipe',
})
export class RemovehtmltagsPipe implements PipeTransform {
/**
* Takes a value and makes it lowercase.
*/
transform(value: string) {
if (value) {
let result = value.replace(/<\/?[^>]+>/gi, "");
return result;
}
else {
}
}
}
Then i added the pipe as export in my component's module.ts
details.module.ts was like so
import { NgModule, CUSTOM_ELEMENTS_SCHEMA } from '#angular/core';
import { IonicPageModule } from 'ionic-angular';
import { DetailsPage } from './details';
import { RemovehtmltagsPipe } from
'../../pipes/removehtmltags/removehtmltags';
#NgModule({
declarations: [
DetailsPage,
],
imports: [
IonicPageModule.forChild(DetailsPage),
],
exports: [RemovehtmltagsPipe],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
})
export class DetailsPageModule {}
Finally used the pipe inside my html code
details.html
<ion-row class="white-bg" padding>
<ion-col>
<h1 class="title">{{article.title.rendered | RemovehtmltagsPipe}}</h1>
<p class="date">Published: {{article.modified.split('T')[0]}} {{article.modified.split('T')[1]}}</p>
</ion-col>
</ion-row>
This should get rid of any html tags in your post.Hope this helps
I'm using the streaming media plugin in my ionic2 application.
this is my code:
let option:StreamingAudioOptions = {
successCallback: () => { console.log('Audio played') },
errorCallback: (e) => { console.log(JSON.stringify(e,null,2)) }
}
this.streamingMedia.playAudio('http://sounddible.com/grab.php?id=2196&type=mp3',option);
the errorCallback return "Class not found"
Any help for explain the reason of this log
Thanks.
try below code :
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import { StreamingMedia, StreamingAudioOptions } from '#ionic-native/streaming-media';
#Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController,private streamingMedia: StreamingMedia) {}
startAudio(){
let options: StreamingAudioOptions = {
successCallback: () => { console.log('Video played') },
errorCallback: (e) => { console.log(JSON.stringify(e,null,2)) },
initFullscreen:false,
};
this.streamingMedia.playAudio('YOUR_URL', options);
}
I am using Camera plugin in Ionic 2 for uploading photos. I am running the app on an Android device. The Carema capture is displayed in the app but when selected from Gallery the photo is not displayed.
The following methods are used for Camera and Gallary:
private openCamera(){
var options: CameraOptions = {
sourceType: this.camera.PictureSourceType.CAMERA,
destinationType: this.camera.DestinationType.DATA_URL,
allowEdit: true,
saveToPhotoAlbum: true
};
this.camera.getPicture(options).then((imageData) => {
this.cameraData = 'data:image/jpeg;base64,' + imageData;
this.photoTaken = true;
this.photoSelected = false;
let base64Image = 'data:image/jpeg;base64,' + imageData;
}, (err) => {
// Handle error
});
}
private selectFromGallery() {
var options = {
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY,
destinationType: this.camera.DestinationType.FILE_URI
};
this.camera.getPicture(options).then((imageData) => {
this.cameraUrl = imageData;
this.photoSelected = true;
this.photoTaken = false;
}, (err) => {
// Handle error
});
}
Following is the code to display in HTML page:
<img [src]="cameraData" *ngIf="photoTaken">
<img [src]="cameraUrl" *ngIf="photoSelected">
You need to use a file plugin to obtain local filesystem url when you select from library.
To install:
$ ionic cordova plugin add cordova-plugin-file
$ npm install --save #ionic-native/file
Import:
import { File } from '#ionic-native/file';
and in your code:
constructor( private file: File, .... ) {}
.....
const options: CameraOptions = {
destinationType: this.camera.DestinationType.FILE_URI,
sourceType: this.camera.PictureSourceType.PHOTOLIBRARY
}
this.camera.getPicture(options).then((imageURI) => {
this.file.resolveLocalFilesystemUrl(imageURI).then(fileEntry => {
this.cameraUrl = fileEntry.nativeURL;
this.photoSelected = true;
this.photoTaken = false;
});
}, (err) => {
// Handle error
});
EDIT
You might need to sanitize the value for img src:
<img *ngIf="cameraUrl" [src]="sanitizeUrl(cameraUrl)" />
The function:
import { DomSanitizer } from '#angular/platform-browser';
....
constructor( private sanitizer: DomSanitizer, .... ) {}
....
sanitizeUrl(url) {
return this.sanitizer.bypassSecurityTrustUrl(url);
}
I am new to Ionic framework and Angular2. I am unable to send post request to the server. I can't figure out what thing I am missing.
My App code:
import { Component } from '#angular/core';
import { NavController } from 'ionic-angular';
import {Camera} from 'ionic-native';
import { Http, Headers, HTTP_PROVIDERS } from 'angular2/http';
import 'rxjs/Rx';
#Component({
selector: 'page-upload',
templateUrl: 'upload.html'
})
export class UploadPage {
public base64Image: string;
array = Array<any>;
loading: boolean;
constructor(public navCtrl: NavController,public http: Http) {
}
takePicture(){
Camera.getPicture({
destinationType: Camera.DestinationType.DATA_URL,
targetWidth: 1000,
targetHeight: 1000
}).then((imageData) => {
// imageData is a base64 encoded string
this.base64Image = "data:image/jpeg;base64," + imageData;
}, (err) => {
console.log(err);
});
}
accessGallery(){
Camera.getPicture({
sourceType: Camera.PictureSourceType.SAVEDPHOTOALBUM,
destinationType: Camera.DestinationType.DATA_URL
}).then((imageData) => {
this.base64Image = 'data:image/jpeg;base64,'+imageData;
}, (err) => {
console.log(err);
});
}
makePostRequest() {
this.http.get('https://public-api.wordpress.com/rest/v1.1/freshly-pressed/').subscribe(data => {
});
}
}
When I compile the app for android I get the following error:
L16: constructor(public navCtrl: NavController,public http: Http) {
Cannot find name 'Http'.
I checked one of my Ionic 2 projects and your imports should be
import {Http, Headers, RequestOptions, Response} from '#angular/http';
check your package.json and fix your project dependencies. You could use this project for references
https://github.com/driftyco/ionic-conference-app/blob/master/package.json