I made some Cordova and Ionic 1 applications in the last few years and really liked the simplicity of cross-platform development.

I’m really excited about the new Ionic 2 framework, which was recently released. They switched AngularJS version to Angular version 2.

After reading many posts about the new features and digging into the Ionic docs, I decided to make a simple Ionic 2 app with some native plugins (Camera, Google Maps and GPS Location).

The best thing?

I didn’t have to deal with any backend development because I used Firebase real time database.

In this post, I show you how to integrate the most requested native features with Ionic 2 framework and create a cross-platform application.

This post is part of a series. From this, you will learn how to:

Ionic 2 App 2

Setup Ionic 2 App and Take a Photo with a Native Camera

For building cross-platform mobile applications with Ionic 2, the easiest way is to use Ionic-CLI, which is included in the Ionic npm package. You have to install Ionic as a global dependency by using this command:

npm i -g ionic

For using the native plugins, Ionic 2 uses Cordova integrations, which can be installed through npm:

npm i -g cordova

After installing these two main frameworks, you can easily start a new project from CLI. This could take a few minutes.

My application name will be ionic-photo-maps, and the --v2 flag means we want to generate an Ionic 2 app with Angular version 2 (without this flag, an Ionic 1 project would be generated, which uses Angular 1).

ionic start ionic-photo-maps --v2

You can test the generated app with the ionic serve command, which will run in your main browser.  If you are building the layout for the app, this will be enough, but most of the native Cordova plugins only work on a real device or on an emulator.

To use an Andriod phone or an emulator, you should add the Android Cordova platform with this command:

ionic platform add android

Help us spread the love and share this post! 🚀

Deploying the Application on an Emulator and a Device

Deploy to Android

You have to get the Android sdk installed on your computer. If it hasn’t been installed yet, you can download it here.

Use this command to install and run on Android:

ionic run android --device

You can use an emulator for an Android deploy. Ionic can deploy your application to the default Android emulator or a Genymotion emulator.

Deploy to iOS (only works on MacOS)

If you don’t have an iOS device, you can only test the application with an iOS simulator.

First, you will need to add the iOS platform to your application with the ionic platform add ios command. This will generate an XCode project for you. If you miss this step, the next command will raise an error, like this one:

Error: The provided path "/some-path-to-project/platforms/ios" is not a Cordova iOS project.

To run the project on your device with ionic-cli, you will need to install iOS-deploy through npm. You will receive a warning message with this information if you type the Ionic run iOS command.

Install ios-deploy to deploy iOS applications to devices.  `npm install -g ios-deploy` (may require sudo)

But, if you have an XCode installed, it contains an iOS simulator and the run command will fall back from device deploying to simulator deploying.

It doesn’t guarantee that every native plugin will work correctly on the simulator, but I tested the location and Google Maps plugin, and I had no issues with them.

There are also some useful commands for the app deploy flow in the Ionic docs.

Ionic 2 App Structure

Next, I want to customize the generated files. The blank Ionic project has one page, which is the root component called Home. We can modify this, remove and make our own root page for the application’s home page. I decided to modify this generated page.

I modified the homepage with navigation cards. The card list now contains one element. This will send us to the Photo Page. Here, we can make photos with the native camera plugin and show a preview as base64 image string.

My home page’s html looks like this code snippet:

<ion-content class="card-background-page">
  <ion-card (click)="goPhotoPage()">
    <img src="assets/images/photo-menu-bg.jpg"/>
    <div class="card-title">Take a picture</div>
  </ion-card>
</ion-content>

In the HTML, I have this line:

<img src="assets/images/photo-menu-bg.jpg"/>

I’m using a static image from the assets folder for the navigation card.

To properly use static assets in your project, here is some detailed information.

Note: the DOM contains only one function: the goPhotoPage() which we need to add to the home.ts :

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { PhotoPage } from './../photo/photo';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
  constructor(
    public navCtrl: NavController
  ) {}
 
  goPhotoPage() { // Added function
    this.navCtrl.push(PhotoPage)
  }
}

We have to make a navigation to the photo page from the home page. For this, we will use the NavController provided by Ionic. The navCtrl.push(page), will push a page to the history stack and navigate the application to that.

To make all of this work, we need to make a new page for the camera plugin. For this, we need to make the file structure under the src/pages folder.

With Ionic-CLI V2, you can use the Ionic generator to simplify this step. Just run this: 

ionic generate page Photo

The Photo Page is an html file and its angular component is mainly blank. You can modify the photo.html

<ion-header>
  section as you want.
</ion-header>
<ion-content padding>
  ...
</ion-content>

And the related component code:

import { Component } from '@angular/core';
 
@Component({
  selector: 'page-photo',
  templateUrl: 'photo.html'
})
export class PhotoPage {
  constructor() {}
}

Before we can use this page, we must register it in the app.module.ts. You need to declare it in the declarations array and in the entryComponents.

...
import { PhotoPage } from '../pages/photo/photo'; // Inject the new page component
 
@NgModule({
  declarations: [
    ...
    PhotoPage  // Declare the PhotoPage for the app
  ],
  ...
  entryComponents: [
    ...
    PhotoPage // Add the PhotoPage as an entry
  ],
  …
})
export class AppModule {}

For now, we can navigate to the new page from the app.

I don’t want to describe the used styling on the elements, but you can check those in the project’s repository on GitHub.

Setup the Native Camera Plugin with Ionic 2

Let’s install the Cordova camera plugin with this command:

ionic plugin add cordova-plugin-camera

Then we can include the camera module into our PhotoPage component:

import { Camera } from 'ionic-native';

To the picture, we need to setup some configurations for the camera. This is a very minimal config, but you can find additional properties in the Ionic native docs.

takePicture() {
  Camera.getPicture({
    correctOrientation: true,
    destinationType: Camera.DestinationType.DATA_URL,
  }).then((imageData) => {
    this.base64Image = 'data:image/jpeg;base64,' + imageData;
  }, (err) => {
    console.error(err);
  });
}

This module can have some quirks because my camera app always started with FRONT camera active, but the doc says you can define the starting camera with this code:

cameraDirection: Camera.Direction.BACK / FRONT (BACK is the default)

But when the camera starts, you can switch the active camera normally.

As you can see, I stored the picture’s base64 data in the base64Image variable and use it in the Html as normal src attribute, like:

<ion-card>
  <img [src]="base64Image"/>
</ion-card>

But, there is an issue with this. I realized that the image couldn’t be found when I started the app.

We need to sanitize the base64 string with the DomSanitizer service.

We can import it into the PhotoPage component

import { DomSanitizer } from '@angular/platform-browser';

and use it with the dependency injection in the constructor:

constructor(
  …
  private DomSanitizer: DomSanitizer
) {}

And replace the html like this:

<ion-card>
  <img [src]="DomSanitizer.bypassSecurityTrustUrl(base64Image)"/>
</ion-card>

After these steps, we can run our application, take a photo and see the preview. The next step will be implementing a persistence layer with local storage and managing the saved photos.

From the next part, you  will see how to manage images in the application’s local storage and create a list view from those.


State of Software Develoopment Report