17. Ionic

17.1. Ionic 4 Getting started

Ionic is a front-end focused framework which offers different tools for developing hybrid mobile applications. The web technologies used for this purpose are CSS, Sass, HTML5 and Typescript.

17.1.1. Why Ionic?

Ionic is used for developing hybrid applications, which means not having to rely on a specifyc IDE such as Android Studio or Xcode. Furthermore, development of native apps require learning different languages (Java/Kotlin for Android and Objective-C/Swift for Apple), with Ionic, a developer does not have to code the same functionality for multiple platforms, just use the adecuate libraries and components.

17.1.2. Basic environment set up

Install Ionic CLI

Although the devonfw distribution comes with and already installed Ionic CLI, here are the steps to install it. The instalation of Ionic is easy, just one command has to be written:

npm install -g ionic

Update Ionic CLI

To update the installed version of the CLI run:

npm install -g ionic@latest

If the devonfw’s ionic CLI has to be updated, the steps are a little bit different:

  • open the devonfw bundled console.

  • cd [devonfw_dist_folder]

  • cd software/nodejs

  • npm uninstall ionic --no-save

  • npm install ionic@latest --no-save

devonfw’s Ionic CLI uptaded

17.2. Basic proyect set up

The set up of an ionic application is pretty inmediate and can be done in one line:

ionic start <name> <template> --type=angular

  • ionic start: Command to create an app.

  • <name>: Name of the application.

  • <template>: Model of the application.

  • --type=angular: With this flag, the app produced will be based on angular.

To create an empty project, the following command can be used:

ionic start MyApp blank --type=angular

Ionic blank project

The image above shows the directory structure generated.

There are more templates available that can be seen with the command ionic start --list

List of ionic templates

The templates surrounded by red line are based on angular and comes with Ionic v4, while the others belong to earlier versions (before v4).

17.3. Ionic 4 to android

This page is written to help developers to go from the source code of an ionic application to an android one, with this in mind, topics such as: environment, commands, modifications,…​ are covered.

17.3.1. Assumptions

This document assumes that the reader has already:

  • Source code of an ionic 4 application and wants to build it on an android device,

  • A working installation of Node.js

  • An Ionic CLI installed and up-to-date.

  • Android Studio and Android SDK.

17.3.2. From ionic 4 to Android project

When a native application is being dessigned, sometimes, functionalities that uses camera, geolocation, push notification, …​ are requested. To resolve these requests, Capacitor can be used.

In general terms, Capacitor wraps apps made with Ionic (HTML, SCSS, Typescript) into WebViews that can be displayed in native applications (Android, IOS) and allows the developer to access native functionalities like the ones said before.

Installing capacitor is as easy as installing any node module, just a few commands have to be run in a console:

  • cd name-of-ionic-4-app

  • npm install --save @capacitor/core @capacitor/cli

Then, it is necessary to initialize capacitor with some information: app id, name of the app and the directory where your app is stored. To fill this information, run:

  • npx cap init

Modifications

Throughout the development process, usually back-end and front-end are on a local computer, so it’s a common practice to have diferent configuration files for each environment (commonly production and development). Ionic 4 uses an angular.json file to store those configurations and some rules to be applied.

If a back-end is hosted on http://localhost:8081, and that direction is used in every environment, the application built for android will not work because computer and device do not have the same localhost. Fortunately, different configurations can be defined.

Android Studio uses 10.0.0.2 as alias for 127.0.0.1 (computer’s localhost) so adding http//10.0.0.2:8081 in a new environment file and modifying angular.json accordingly, will make possible connect front-end and back-end.

Android environment and angular.json
"build": {
...
    "configurations": {
        ...
        "android": {
            "fileReplacements": [
                {
                    "replace": "src/environments/environment.ts",
                    "with": "src/environments/environment.android.ts"
                }
            ]
        },
    }
}
Build

Once configured, it is necessary to build the Ionic 4 app using this new configuration:

  • ionic build --configuration=android

The next commands copy the build application on a folder named android and open android studio.

  • npx cap add android

  • npx cap copy

  • npx cap open android

17.3.3. From Android project to emulated device

Once Android Studio is opened, follow these steps:

  1. Click on "Build" → Make project.

  2. Click on "Build" → Make Module 'app' (default name).

Click on make project click on make app

  1. Click on" Build" → Build Bundle(s) / APK(s) → Build APK(s).

  2. Click on run and choose a device.

click on build APK click on running device

If there are no devices available, a new one can be created:

  1. Click on "Create new device"

  2. Select hardware and click "Next". For example: Phone → Nexus 5X.

Create new device Select hardware

  1. Download a system image.

    1. Click on download.

    2. Wait until the installation finished and then click "Finish".

    3. Click "Next".

  2. Verify configuration (default configuration should be enough) and click "Next".

Download system image Check configuration

  1. Check that the new device is created correctly.

New created device

17.3.4. From Android project to real device

To test on a real android device, an easy aproach to comunicate a smartphone (front-end) and computer (back-end) is to configure a Wi-fi hotspot and connect the computer to it. A guide about this process can be found at https://support.google.com/nexus/answer/9059108?hl=en

Once connected, run ipconfig on a console if you are using windows or ifconfig on a linux machine to get the IP address of your machine’s Wireless LAN adapter Wi-fi.

Result of ipconfig command on Windows 10

This obtained IP must be used instead of "localhost" or "10.0.2.2" at environment.android.ts.

Android environment file server URL

After this configuration, follow the build steps in "From ionic 4 to Android project" and the first three steps in "From Android project to emulated device".

Send APK to Android through USB

To send the built application to a device, you can connect computer and mobile through USB, but first, it is necessary to unlock developer options.

  1. Open "Settings" and go to "System".

  2. Click on "About".

  3. Click "Build number" seven times to unlock developer options.

Steps to enable developer options: 1, 2, 3
  1. Go to "System" again an then to "Developer options"

  2. Check that the options are "On".

  3. Check that "USB debugging" is activated.

Steps to enable developer options: 4, 5, 6

After this, do the step four in "From Android project to emulated device" and choose the connected smartphone.

Send APK to Android throught email

When you build an APK, a dialog gives two options: locate or analyze. If the first one is chosen, Windows file explorer will be opened showing an APK that can be send using email. Download the APK on your phone and click it to install.

Steps to enable developer options: 4, 5, 6

17.3.5. Result

If everything goes correctly, the Ionic 4 application will be ready to be tested.

Application running on a real device

17.4. Ionic Progressive Web App

This guide is a continuation of the guide Angular PWAs, therefore, valid concepts explained there are still valid in this page but focused on Ionic.

17.4.1. Assumptions

This guide assumes that you already have installed:

  • Node.js

  • npm package manager

  • Angular CLI

  • Ionic 4 CLI

  • Capacitor

Also, it is a good idea to read the document about PWA using Angular.

17.4.2. Sample Application

Ionic 4 PWA Base
Figure 67. Basic ionic PWA.

To explain how to build progressive web apps (PWA) using Ionic 4, a basic application is going to be built. This app will be able to take photos even without network using PWA elements.

Step 1: Create a new project

This step can be completed with one simple command: ionic start <name> <template>, where <name> is the name and <template> a model for the app. In this case, the app is going to be named basic-ion-pwa.

Step 2: Structures and styles

The styles (scss) and structures (html) do not have anything specially relevant, just colors and ionic web components. The code can be found in devon4ng samples.

Step 3: Add functionality

After this step, the app will allow users take photos and display them in the main screen. First we have to import three important elements:

  • DomSanitizer: Sanitizes values to be safe to use.

  • SafeResourceUrl: Interface for values that are safe to use as URL.

  • Plugins: Capacitor constant value used to access to the device’s camera and toast dialogs.

  import { DomSanitizer, SafeResourceUrl } from '@angular/platform-browser';
  import { Plugins, CameraResultType } from '@capacitor/core';
  const { Camera, Toast } = Plugins;

The process of taking a picture is enclosed in a takePicture method. takePicture calls the Camera’s getPhoto function which returs an URL or an exception. If a photo is taken then the image displayed in the main page will be changed for the new picture, else, if the app is closed without changing it, a toast message will be displayed.

  export class HomePage {
    image: SafeResourceUrl;
    ...

    async takePicture() {
      try {
        const image = await Camera.getPhoto({
          quality: 90,
          allowEditing: true,
          resultType: CameraResultType.Uri,
        });

        // Change last picture shown
        this.image = this.sanitizer.bypassSecurityTrustResourceUrl(image.webPath);
      } catch (e) {
        this.show('Closing camera');
      }
    }

    async show(message: string) {
      await Toast.show({
        text: message,
      });
    }
  }
Step 4: PWA Elements

When Ionic apps are not running natively, some resources like Camera do not work by default but can be enabled using PWA Elements. To use Capacitor’s PWA elements run npm install @ionic/pwa-elements and modify src/main.ts as shown below.

...

// Import for PWA elements
import { defineCustomElements } from '@ionic/pwa-elements/loader';

if (environment.production) {
  enableProdMode();
}

platformBrowserDynamic().bootstrapModule(AppModule)
  .catch(err => console.log(err));

// Call the element loader after the platform has been bootstrapped
defineCustomElements(window);
Step 5: Make it Progressive.

Turining an ionic 4 app into a PWA is pretty easy, the same module used to turn Angular apps into PWAs has to be added, to do so, run: ng add @angular/pwa. This command also creates an icons folder inside src/assets and contains angular icons for multiple resolutions. If you want use other images, be sure that they have the same resolution, the names can be different but the file manifest.json has to be changed accordingly.

Step 6: Configure the app

manifest.json

Default configuration.

ngsw-config.json

At assetGroups → resources add a urls field and a pattern to match PWA Elements scripts and other resources (images, styles, …​):

  "urls": ["https://unpkg.com/@ionic/pwa-elements@1.0.2/dist/**"]
Step 7: Check that your app is a PWA

To check if an app is a PWA lets compare its normal behaviour against itself but built for production. Run in the project’s root folder the commands below:

ionic build --prod to build the app using production settings.

npm install http-server to install an npm module that can serve your built application. Documentation here.

Go to the www folder running cd www.

http-server -o to serve your built app.

Http server running
Figure 68. Http server running on localhost:8081.

 
In another console instance run ionic serve to open the common app (not built).

Ionic serve on Visual Studio Code console
Figure 69. Ionic server running on localhost:8100.

 
The first difference can be found on Developer tools → application, here it is seen that the PWA application (left) has a service worker and the common one does not.

Application comparison
Figure 70. Application service worker comparison.

 
If the "offline" box is checked, it will force a disconnection from network. In situations where users do not have connectivity or have a slow, one the PWA can still be accesed and used.

Online offline apps
Figure 71. Offline application.

 
Finally, plugins like Lighthouse can be used to test whether an application is progressive or not.

Lighthouse report
Figure 72. Lighthouse report.
Last updated 2019-12-11 12:58:44 UTC