Nikola Brežnjak blog - Tackling software development with a dose of humor
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Home
Daily Thoughts
Ionic
Stack Overflow
Books
About me
  • Home
  • Daily Thoughts
  • Ionic
  • Stack Overflow
  • Books
  • About me
Nikola Brežnjak blog - Tackling software development with a dose of humor
Ionic3, JavaScript

How to create an Android Cordova plugin for showing Toast popups

TL;DR

In this post, I’m going to show you step by step how to build a Cordova plugin for Android that shows a native Toast popup.

You can check out the source code of the plugin here and the source of the demo Ionic app that’s using this plugin here.

In case you’re looking for the guide on how to write the Cordova plugin for the iOS platform, I wrote about it here.

plugin.xml

We start the process of plugin building by creating the plugin.xml file:

<?xml version='1.0' encoding='utf-8'?>
<plugin id="cordova-android-toast" version="1.0.0" xmlns="http://apache.org/cordova/ns/plugins/1.0" xmlns:android="http://schemas.android.com/apk/res/android">
    <name>AndroidToast</name>

    <description>Android Toast Plugin</description>
    <license>Apache 2.0</license>
    <keywords>android, toast</keywords>

    <engines>
      <engine name="cordova" version=">=3.0.0" />
    </engines>

    <js-module name="AndroidToast" src="www/AndroidToast.js">
        <clobbers target="AndroidToast" />
    </js-module>

    <platform name="android">
        <config-file target="config.xml" parent="/*">
            <feature name="AndroidToast">
                <param name="android-package" value="com.nikolabreznjak.AndroidToast" />
            </feature>
        </config-file>

        <source-file src="src/android/AndroidToast.java" target-dir="src/com/nikola-breznjak/android-toast" />
    </platform>
</plugin>

In this file you basically define:

  • the platform this plugin supports (<platform name="android">)
  • where the source files of your plugin will be (source-file elements)
  • where is the JavaScript file that will be the bridge from Cordova to native code (js-module tag src property)
  • what will be the plugin’s name by which you’ll reference it in the Cordova/Ionic code (<clobbers target="AndroidToast" />)

www/AndroidToast.js

Next comes the so-called ‘bridge’ file that connects the native and JavaScript side. It is common to put this file in the www folder. The contents of this file is as follows:

var exec = cordova.require('cordova/exec');

var AndroidToast = function() {
    console.log('AndroidToast instanced');
};

AndroidToast.prototype.show = function(msg, onSuccess, onError) {
    var errorCallback = function(obj) {
        onError(obj);
    };

    var successCallback = function(obj) {
        onSuccess(obj);
    };

    exec(successCallback, errorCallback, 'AndroidToast', 'show', [msg]);
};

if (typeof module != 'undefined' && module.exports) {
    module.exports = AndroidToast;
}

We created the AndroidToast function, which in other programming languages would basically be a class, because we added the show function on its prototype. The show function, via Cordova’s exec function, registers the success and error callbacks for the AndroidToast class and the show method on the native side that we’ll show now shortly. Also, we pass in the msg variable as an array to the native show function.

src/android/AndroidToast.java

The ‘native’ code is written in Java:

package com.nikolabreznjak;

import org.apache.cordova.CordovaPlugin;
import org.apache.cordova.CallbackContext;
import org.json.JSONArray;
import org.json.JSONObject;
import org.json.JSONException;
import android.content.Context;
import android.widget.Toast;

public class AndroidToast extends CordovaPlugin {
    @Override
    public boolean execute(String action, JSONArray args, CallbackContext callbackContext) throws JSONException {
        if ("show".equals(action)) {
            show(args.getString(0), callbackContext);
            return true;
        }

        return false;
    }

    private void show(String msg, CallbackContext callbackContext) {
        if (msg == null || msg.length() == 0) {
            callbackContext.error("Empty message!");
        } else {
            Toast.makeText(webView.getContext(), msg, Toast.LENGTH_LONG).show();
            callbackContext.success(msg);
        }
    }
}

In the implementation file, we define our functions. We only have the show and execute functions in our example. When writing Cordova plugins for Android, every function from the bridge file has to call the exec function, which then calls the execute function on the native side. Then, based on the action parameter, we decide which function needs to be called. In our case, if we determine that the show action was called, we pass through the arguments to the private show function, which then uses the native Toast.makeText function to display the Toast message.

When displaying the Toast, our show method needs access to the app’s global Context, which can be obtained using the webView object that we get from extending CordovaPlugin. This represents the running Cordova app, and we can get the global Context from there using: webView.getContext(). Other parameters to the makeText function define the text that we want to show and the duration of how long we want to show it.

At this point you could customize the toast as much as the native Toast component allows, there are no restrictions even though this is used via Cordova as a kind of a ‘wrapper’. Some additional stuff that you could do is listed in the official documentation.

package.json

In earlier versions of Cordova, this file wasn’t required. You can generate it automatically with the help of the plugman package (install it with npm install plugman -g in case you don’t have it):

plugman createpackagejson /path/to/your/plugin.

If you’re in the plugin folder, then the command is: plugman createpackagejson .. The package.json file in my case now looks like this:

{
    "name": "cordova-android-toast",
    "version": "1.0.0",
    "description": "Android Toast Plugin",
    "cordova": {
        "id": "cordova-android-toast",
        "platforms": [
            "android"
        ]
    },
    "keywords": [
        "android",
        "toast",
        "ecosystem:cordova",
        "cordova-android"
    ],
    "engines": [{
        "name": "cordova",
        "version": ">=3.0.0"
    }],
    "author": "Nikola Brežnjak<[email protected]> (http://www.nikola-breznjak.com/blog)",
    "license": "Apache 2.0"
}

Using the plugin

First, you need to install it. If you’re using Ionic:

ionic cordova plugin add cordova-android-toast

If you’re using Cordova:

cordova plugin add cordova-android-toast

In the code, you would show the toast message like this:

constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
        platform.ready().then(() => {
            var androidToast = new AndroidToast();
            androidToast.show(
                'This is some nice toast popup!',
                function(msg) {
                    console.log(msg);
                },
                function(err) {
                    console.log(err);
                }
            );

        });
    }

If you’re using the newest (currently 3) version of Ionic, then you would have to add this line: declare var AndroidToast: any; after the imports in app.component.ts (or any other file where you’ll use the plugin) before actually using it. If you’re using Ionic 1, you don’t need to do this.

As a final note, make sure you’re accessing the plugin after the platform.ready() fires, just so you make sure that the plugin is ready for use.

Running the demo locally

Clone this repo:

git clone https://github.com/Hitman666/cordova-android-toast.git

CD into the cloned project

cd cordova-android-toast

Install the dependencies:

npm install && bower install

Add the Android platform (please note that this process may take a while to complete):

ionic cordova platform add android

Add the plugin:

ionic cordova plugin add cordova-android-toast

Run the project on the device (if you have it connected):

ionic cordova run android

Run the project on the emulator:

ionic cordova emulate android

You should see something like this once the app runs on your device:

Conclusion

I hope this post gave you enough information so that you’ll be dangerous enough to go and fiddle with the Android Cordova plugin building yourself ?

If you have any questions, feel free to reach out.

Ionic3

How to polish our existing Ionic3 calculator application

This is the third post in a series of posts which will teach you how to take advantage of your web development knowledge in building hybrid applications for iOS and Android. The first post in this series was all about How to get started with Ionic framework 3 on Windows and Mac, the second one was about How to create a calculator application with Ionic framework 3 by using Ionic Creator for UI.

In this post you’ll learn:

  • How to polish your existing calculator application
  • How to create icons and splash screen images automatically
  • How to implement Google AdMob ads
  • How to share your application with other users without going through the app stores
  • How to test your application on the real physical devices and emulators

So, if you’ve been following these series of posts then you probably already have the Calculator application ready and running on your machine in the web browser by using the ionic lab command.

If you just dropped by, or you would like to start from scratch, then you can clone the finished version of the 2nd tutorial from Github. After cloning, you have to run npm install to install all the dependencies. After this, the command ionic lab should run the application locally on your computer, and you should see it open up in your default browser. Of course, all this should work if you have Ionic properly installed. If not, please check out the instructions in the first tutorial.

At this point, we have a working simple calculator application that lacks some sanitization checks and design improvements. We’ll fix that in this section.

Sanitization check

In our current application, we don’t have a security measure against the possible malformed input. For example, one could enter two plus (+) signs one after another, which would consequently produce an error.

So, to handle this, we’re going to wrap our evaluation line of code in the try/catch block, and we’re going to show an alert to the user using the AlertController dialog (injected as a dependency in the CalculatorPage class constructor). The whole contents of the calculator.ts file should look like this now:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AlertController } from 'ionic-angular';

@Component({
    selector: 'page-calculator',
    templateUrl: 'calculator.html'
})
export class CalculatorPage {
    constructor(public navCtrl: NavController, private alertCtrl: AlertController) { }

    result = '';

    btnClicked(btn) {
        if (btn == 'C') {
            this.result = '';
        }
        else if (btn == '=') {
            if (this.result == '') {
                return;
            }

            try {
                this.result = eval(this.result).toFixed(2);
            } catch (error) {
                this.showAlert();
                this.result = '';
            }
        }
        else {
            this.result += btn;
        }
    }

    showAlert() {
        this.alertCtrl.create({
            title: 'Malformed input',
            subTitle: 'Ooops, please try again...',
            buttons: ['Dismiss']
        }).present();
    }
}

Additionally, we’re checking to see if the result variable contains anything at the time the equals button is pressed, to avoid the undefined error that would otherwise happen. You can test this yourself by running the application clicking the equals button = and then on, for example, button 5, and you will see the text undefined5 appear in the Result area.

Also, you may have noticed that we added the toFixed(2) after our eval function call, to show the result formatted to two decimal places.

If you intentionally make an error while inputting the formula you would get this message:

Clearly, there are multiple ways you could approach this problem further to create a better user experience. One idea is to check on every button click if the current formula would execute correctly with eval and if not then immediately inform the user, or completely ignore the last clicked button. I encourage you to create your own way of the “improved UX” and share it in the comments.

Design changes

To be honest, our app currently doesn’t look quite representative. We’re going to change that to make it a bit nicer. If you ask any web designer these days, they will tell you that using pure CSS is, well, outdated. Ionic, as awesome as it is, has support for SASS out of the box so you can take advantage of the variables, nesting, mixins and all other great stuff that SASS provides.

For example, if you want to change the color you only need to change one variable, without having to trace it through all the files and change the particular color in all the places that it is used.

In the previous tutorial we added the ‘energized’ color to the colors array in the src/theme/variables.scss file. Now we’re going to do all of our changes in the pages/calculator/calculator.scss file, which, for now, looks like this:

page-calculator {

}

These changes will only apply to this page. If we’d like to add some styles that would apply to our whole app, we can do so in the src/app/app.scss file.

On the image below you can see what I came up with after changing few of the CSS rules, (and a slight addition to our HTML template that I’ll address additionally):

I’m sure that more design-inclined readers will come up with way more slick design than this and I encourage you to share your images/scss changes with the rest of us.

Now we’re going to go through the parts that were changed so that you can follow along in your example and see for yourself.

As for the changes, here is the final content of the src/pages/calculator/calculator.html file:

<ion-header>
    <ion-navbar>
        <ion-title>
            SuperSimple Calculator
        </ion-title>
    </ion-navbar>
</ion-header>

<ion-content>
    <div class="container">
        <form class="myInputRow">
            <ion-item>
                <ion-input type="text" placeholder="0" name="display" [(ngModel)]="result"></ion-input>
            </ion-item>
        </form>

        <div class="row">
            <button class="col2" ion-button color="danger" (click)="btnClicked('C')"> C </button>
            <button class="col" ion-button color="energized" (click)="btnClicked('%')"> % </button>
            <button class="col" ion-button color="energized" (click)="btnClicked('/')"> / </button>
        </div>

        <div class="row">
            <button class="col" ion-button (click)="btnClicked('7')"> 7 </button>
            <button class="col" ion-button (click)="btnClicked('8')"> 8 </button>
            <button class="col" ion-button (click)="btnClicked('9')"> 9 </button>
            <button class="col" ion-button color="energized" (click)="btnClicked('*')"> * </button>
        </div>

        <div class="row">
            <button class="col" ion-button (click)="btnClicked('4')"> 4 </button>
            <button class="col" ion-button (click)="btnClicked('5')"> 5 </button>
            <button class="col" ion-button (click)="btnClicked('6')"> 6 </button>
            <button class="col" ion-button color="energized" (click)="btnClicked('-')"> - </button>
        </div>

        <div class="row">
            <button class="col" ion-button (click)="btnClicked('1')"> 1 </button>
            <button class="col" ion-button (click)="btnClicked('2')"> 2 </button>
            <button class="col" ion-button (click)="btnClicked('3')"> 3 </button>
            <button class="col" ion-button color="energized" (click)="btnClicked('+')"> + </button>
        </div>

        <div class="row">
            <button class="col" ion-button (click)="btnClicked('0')"> 0 </button>
            <button class="col" ion-button (click)="btnClicked('.')"> . </button>
            <button class="col2" ion-button color="danger" (click)="btnClicked('=')"> = </button>
        </div>
    </div>
</ion-content>

Here is the breakdown of the changes that I did:

  • changed the title to SuperSimple Calculator from just Calculator on the ion-title tag
  • removed all the id attributes
  • removed the ion-label in the form element
  • added the myInputRow class to the form element
  • added the row class to the div elements
  • added the col class to the button elements, except + and = buttons to which I’ve added the col2 class
  • wrapped everything in a div with the container class

In the scss/ionic.app.scss file I added the definitions for these new classes:

page-calculator {
    .container {
        display: flex;
        flex-direction: column;
        height: 100%;

        .row {
            flex: 2;
            flex-direction: row;
            padding: 0px !important;
            margin: 0px !important;

            .col {
                flex: 1;
                padding: 0px !important;
                margin: 0px !important;
            }

            .col2 {
                flex: 2;
                padding: 0px !important;
                margin: 0px !important;
            }
        }

        .myInputRow {
            flex: 1 !important;

            input {
                font-size: 40px;
                text-align: right;
            }
        }

        button {
            height: auto !important;
            border-radius: 0px !important;
            font-size: 32px;
            font-weight: bold;
            border-left: 1px solid #fff;
            border-bottom: 1px solid #fff;
        }
    }
}

Flexbox is used here as a basis for making the layout which fills the whole content horizontally. You can learn more about it from this Ionic specific tutorial, or you can learn more about Flexbox in general from this tutorial.

This way we now have an interface which fills the whole available content.

How to create icons and splash screen images automatically in Ionic framework 3

The icon is an important part of your application because it represents your application’s brand, and it helps to identify quickly where the app is on your phone. In case you’re familiar with creating apps then you will remember that it is a tedious process to create a lot of different size images both for iOS and Android platforms.

Also, the same goes for the so-called splash screen that shows up every time the application starts. Although having a splash screen is not mandatory, it certainly adds up to the feeling of a complete and professional application, which one would certainly want to convey with his application.

Ionic helps tremendously with this by providing a single Ionic CLI command to generate all the needed icon and splash screen sizes for us automatically. Also, Ionic created Photoshop Splash Screen Template, which you can download for free and use as a guideline for creating an icon. However, if you create you project by using ionic start command, as we have, then you’ll already have both the icon.png and splash.png files in the resources folder, and you can just edit them.

For when you’re creating a branded product having a custom made icon is definitely a must. However, in this case, I’ll show you how to use one of the free services to search for a free icon which you’ll then use in your application (even if your application is a commercial application).

I tend to use IconFinder a lot, and here are the settings which you have to use to filter out the calculator images that are Free (PRICE) and can be used in commercial applications and that don’t even require a link back (LICENSE TYPE).

Of course, you can also choose to buy an image if you happen to find one that you like. You can additionally search by format, size, and background. The filters should look like this (use this prepared link which sets them automatically):

I’m going to use the last one in the first row. Simply click on it, and you should get to the download page that looks like this:

To download it just click on the green ‘Download PNG’ button.

Now, in the resources folder find and open the icon.png file with an image editor of your choice. I’m going to use Gimp in this example as it’s free cross-platform image editor available for all the major operating systems (Linux, OS X, Windows). You should see something like this:

Now you need to do a few steps:

  • select the whole area (Ctrl + a or Command + a) and press the DEL button on your keyboard. This should leave you with a blank white canvas.
  • drag the calculator icon on this white canvas and you should see something like this:
  • click on the scale tool
  • then click on the calculator image. You should get this popup:
  • change the values in the popup to 1024px for both Width and Height and click the Scale button.
  • click on the Alignment Tool, then click on the calculator image and then on the circled two buttons on the image below. This will align the calculator image horizontally and vertically

Now save the file by going to File->Overwrite icon.png:

Repeat the process to create the splash screen image and name it (overwrite it as) splash.png. The image I came up with looks like this:

Now that you have both icon.png and splash.png images ready, navigate with your Terminal/Command prompt to the root folder of the application and run the following command:

ionic cordova resources

You should get the following output:

✔ Collecting resource configuration and source images - done!
✔ Filtering out image resources that do not need regeneration - done!
✔ Uploading source images to prepare for transformations - done!
✔ Generating platform resources: 48 / 48 complete - done!
✔ Modifying config.xml to add new image resources - done!

If, instead, at this point, you get an error like this:

[ERROR] No platforms have been added. Please run: ionic cordova platform add

That means that you haven’t added any platforms yet to which Ionic should build. Since we’re going to build the app for both Apple Store and Android Play Store we’re going to use the following two commands:

ionic cordova platform add android
ionic cordova platform add ios

You should see an output similar to this:

ionic cordova platform add ios
> cordova platform add ios --save
✔ Running command - done!
Using cordova-fetch for cordova-ios@~4.4.0
Adding ios project...
Creating Cordova project for the iOS platform:
    Path: platforms/ios
    Package: io.ionic.starter
    Name: MyApp
iOS project created with [email protected]
Discovered plugin "cordova-plugin-console" in config.xml. Adding it to the project
Installing "cordova-plugin-console" for ios
Adding cordova-plugin-console to package.json
Saved plugin info for "cordova-plugin-console" to config.xml
Discovered plugin "cordova-plugin-device" in config.xml. Adding it to the project
Installing "cordova-plugin-device" for ios
Adding cordova-plugin-device to package.json
Saved plugin info for "cordova-plugin-device" to config.xml
Discovered plugin "cordova-plugin-splashscreen" in config.xml. Adding it to the project
Installing "cordova-plugin-splashscreen" for ios
Adding cordova-plugin-splashscreen to package.json
Saved plugin info for "cordova-plugin-splashscreen" to config.xml
Discovered plugin "cordova-plugin-statusbar" in config.xml. Adding it to the project
Installing "cordova-plugin-statusbar" for ios
Adding cordova-plugin-statusbar to package.json
Saved plugin info for "cordova-plugin-statusbar" to config.xml
Discovered plugin "cordova-plugin-whitelist" in config.xml. Adding it to the project
Installing "cordova-plugin-whitelist" for ios
Adding cordova-plugin-whitelist to package.json
Saved plugin info for "cordova-plugin-whitelist" to config.xml
Discovered plugin "ionic-plugin-keyboard" in config.xml. Adding it to the project
Installing "ionic-plugin-keyboard" for ios
Adding ionic-plugin-keyboard to package.json
Saved plugin info for "ionic-plugin-keyboard" to config.xml
--save flag or autosave detected
Saving ios@~4.4.0 into config.xml file ...
✔ Copying default image resources into ./resources/ios - done!

> cordova platform add android --save
✔ Running command - done!
Using cordova-fetch for cordova-android@~6.2.2
Adding android project...
Creating Cordova project for the Android platform:
    Path: platforms/android
    Package: io.ionic.starter
    Name: MyApp
    Activity: MainActivity
    Android target: android-25
Subproject Path: CordovaLib
Android project created with [email protected]
Installing "cordova-plugin-console" for android
Installing "cordova-plugin-device" for android
Installing "cordova-plugin-splashscreen" for android
Installing "cordova-plugin-statusbar" for android
Installing "cordova-plugin-whitelist" for android

               This plugin is only applicable for versions of cordova-android greater than 4.0. If you have a previous platform version, you do *not* need this plugin since the whitelist will be built in.

Installing "ionic-plugin-keyboard" for android
--save flag or autosave detected
Saving android@~6.2.3 into config.xml file ...
✔ Copying default image resources into ./resources/android - done!

After this, the ionic cordova resources command should work.

From the output, you can see that 48 images were created and hopefully now you realize how much time this saved. All the needed configuration regarding the icons and splash screens was generated by Ionic and placed in the config.xml file.

It’s worth noting that you will not see the icon nor the splash screen when using the browser testing or Ionic View testing (discussed in more detail in the How to use Ionic.io cloud service to share our application with other users without going through the app store section below). Instead, you will only see these once you deploy them to the actual physical device or the emulator (which we’ll cover in the How to test our application on the real physical devices and emulators section below).

⚠️ You can add an iOS platform if you’re developing on a Windows machine, and ionic cordova resources command will generate icons and splash screens for it. However, keep in mind that you will not be able to build the project for iOS on your Windows machine. Instead, you’ll need a Mac computer to do so. We’ll cover building the app in more detail in the How to test our application on the real physical devices and emulators section below.

How to implement Google AdMob ads

There are multiple ways you can earn money with your app these days and here are just a few:

  • Paid app – set a price for your app directly on the App/Play Store that users need to pay before downloading your app
  • Freemium – give the app for free but charge for in-app purchases like adding some extra features (think more gold or faster production in game apps)
  • Ad-based – show ads inside your application. Potentially offer the in-app purchase to remove the ads

Here we’re going to cover the Ad-based monetization option where I’ll show you how to add Google AdMob ads to our calculator application. There are two parts to implementing Google AdMob ads to an Ionic project, and I broke them into AdMob settings and Ionic settings.

AdMob settings

Let’s start with AdMob settings:

  1. Sign in/Sign up for AdMob at https://www.google.com/admob/
  2. Click the Apps and then ADD APP button:

  1. Since our app is not published yet we will click the No button:

  1. Fill in the app name and platform and click the ADD button:

  1. Save the App ID somewhere and proceed to create the Ad unit

  1. Select Banner Ad format:

  1. Configure the adds type, size, placement, style, name:

  1. You can read additional info on how to implement GA and AdMob, but for now, let’s just click Done:

  1. You will now see the following similar screen:

The most important thing to note here is this Ad unit ID, which in my test case is ca-app-pub-7957971173858308/5068937357. Make a note of this string as it’s the most important part of this setting. You can click on the copy to clipboard button and paste it as a comment (for now) in your app.

  1. Create as much Ad units as you may need (for each platform[iOS, Android] and ad format [Banner, Interstitial, etc.]). In my case, I just created the additional Interstitial Ad and will use them on both iOS and Android devices for this demo.

Ionic settings

Those of you familiar with Ionic 1 know that you can add any plugin to your Ionic project thanks to the project called ngCordova. For Ionic 3, there’s the same thing called Ionic Native.

Ionic Native is a TypeScript wrapper for Cordova/PhoneGap plugins that makes it easy to add any native functionality that you may need into your Ionic app. Ionic Native wraps the plugin callbacks in a Promise or an Observable, providing a common interface for all plugins and ensuring that native events trigger change detection in Angular.

Navigate to the root of the application with your Terminal/Command prompt and execute the following command to add the cordova-plugin-admobpro plugin:

ionic cordova plugin add cordova-plugin-admobpro

You should see the following output after running the command:

> cordova plugin add cordova-plugin-admobpro --save
✔ Running command - done!
Installing "cordova-plugin-admobpro" for android
Installing "cordova-plugin-extension" for android
Subproject Path: CordovaLib
Installing "cordova-plugin-admobpro" for ios
Plugin dependency "[email protected]" already fetched, using that version.
Installing "cordova-plugin-extension" for ios
Adding cordova-plugin-admobpro to package.json
Saved plugin info for "cordova-plugin-admobpro" to config.xml

Additionally, you also need to run this command:

npm install --save @ionic-native/admob-pro

which, if completed successfully, will only output something like added 1 package in 4.443s to the console.

You need to add this second command as well because this installs some files needed by TypeScript.

⚠️ At this point, depending on the version of Ionic CLI that you have you may need to add a platform by executing: ionic cordova platform add ios or ionic cordova platform add android depending on the platform you’re trying to build for. You have to execute that if the command ionic cordova platform ls shows that you don’t have any installed platforms on the current project:

→ ionic cordova platform ls
✔ cordova platform ls - done!
Installed platforms:
Available platforms: 
 android ~6.2.2
 blackberry10 ~3.8.0 (deprecated)
 browser ~4.1.0
 ios 4.4.0
 osx ~4.0.1
 webos ~3.7.0

If everything is fine with running ionic cordova platform add ios you will see an output like this:

Using cordova-fetch for cordova-ios@~4.4.0
Adding ios project...
Creating Cordova project for the iOS platform:
    Path: platforms/ios
    Package: io.ionic.starter
    Name: MyApp
iOS project created with [email protected]
Installing "cordova-plugin-admobpro" for ios
Installing "cordova-plugin-extension" for ios
Discovered plugin "cordova-plugin-console" in config.xml. Adding it to > the project
Installing "cordova-plugin-console" for ios
Adding cordova-plugin-console to package.json
Saved plugin info for "cordova-plugin-console" to config.xml
Discovered plugin "cordova-plugin-device" in config.xml. Adding it to > the project
Installing "cordova-plugin-device" for ios
Adding cordova-plugin-device to package.json
Saved plugin info for "cordova-plugin-device" to config.xml
Discovered plugin "cordova-plugin-splashscreen" in config.xml. Adding > it to the project
Installing "cordova-plugin-splashscreen" for ios
Adding cordova-plugin-splashscreen to package.json
Saved plugin info for "cordova-plugin-splashscreen" to config.xml
Discovered plugin "cordova-plugin-statusbar" in config.xml. Adding it > to the project
Installing "cordova-plugin-statusbar" for ios
Adding cordova-plugin-statusbar to package.json
Saved plugin info for "cordova-plugin-statusbar" to config.xml
Discovered plugin "cordova-plugin-whitelist" in config.xml. Adding it > to the project
Installing "cordova-plugin-whitelist" for ios
Adding cordova-plugin-whitelist to package.json
Saved plugin info for "cordova-plugin-whitelist" to config.xml
Discovered plugin "ionic-plugin-keyboard" in config.xml. Adding it to > the project
Installing "ionic-plugin-keyboard" for ios
Adding ionic-plugin-keyboard to package.json
Saved plugin info for "ionic-plugin-keyboard" to config.xml
--save flag or autosave detected
Saving ios@~4.4.0 into config.xml file ...
✔ Copying default image resources into ./resources/ios - done!

Btw, there is also a free version of the AdMob Pro plugin. But, honestly, if you really start making money with your app, this will be a minor expense. Besides, if you’re having problems giving back to the actual plugin through which you’re making money then my dear padawan you have yet much to learn… ?

Now, let’s add this plugin to our app’s NgModule. In the src/app/app.module.ts file import AdmobPro:

import { AdMobPro } from '@ionic-native/admob-pro';

and then add it to the Providers array. The whole contents of the src/app/app.module.ts file should now looks like this:

import { NgModule, ErrorHandler } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { IonicApp, IonicModule, IonicErrorHandler } from 'ionic-angular';
import { MyApp } from './app.component';
import { CalculatorPage } from '../pages/calculator/calculator';


import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';
import { AdMobPro } from '@ionic-native/admob-pro';

@NgModule({
    declarations: [
        MyApp,
        CalculatorPage
    ],
    imports: [
        BrowserModule,
        IonicModule.forRoot(MyApp)
    ],
    bootstrap: [IonicApp],
    entryComponents: [
        MyApp,
        CalculatorPage
    ],
    providers: [
        StatusBar,
        SplashScreen,
        AdMobPro,
        { provide: ErrorHandler, useClass: IonicErrorHandler }
    ]
})
export class AppModule { }

Now I’m going to show you the final content of the src/pages/calculator/calculator.ts file and will explain what was changed step by step:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
import { AlertController } from 'ionic-angular';

import { AdMobPro } from '@ionic-native/admob-pro';
import { Platform } from 'ionic-angular';

@Component({
    selector: 'page-calculator',
    templateUrl: 'calculator.html'
})
export class CalculatorPage {
    constructor(public navCtrl: NavController, private alertCtrl: AlertController, private admob: AdMobPro, private platform: Platform) {
        this.platform.ready().then(() => {
            var admobid = {
                banner: 'ca-app-pub-7957971173858308/5068937357',
                interstitial: 'ca-app-pub-7957971173858308/5667703151'
            };

            this.admob.createBanner({
                adId: admobid.banner,
                isTesting: true,
                autoShow: true,
                position: this.admob.AD_POSITION.BOTTOM_CENTER
            })

            this.admob.prepareInterstitial({
                adId: admobid.interstitial,
                isTesting: true,
                autoShow: false
            })
        });
    }

    result = '';
    counter = 1;

    showInterstitialAd() {
        if (AdMobPro) {
            this.admob.showInterstitial();
        }
    }

    btnClicked(btn) {
        if (btn == 'C') {
            this.result = '';
        }
        else if (btn == '=') {
            if (this.result == '') {
                return;
            }

            try {
                this.result = eval(this.result).toFixed(2);

                if (this.counter++ == 5) {
                    this.showInterstitialAd();
                    this.counter = 0;
                }
            } catch (error) {
                this.showAlert();
                this.result = '';
            }
        }
        else {
            this.result += btn;
        }
    }

    showAlert() {
        this.alertCtrl.create({
            title: 'Malformed input',
            subTitle: 'Ooops, please try again...',
            buttons: ['Dismiss']
        }).present();
    }
}

First, we added the imports:

import { AdMobPro } from '@ionic-native/admob-pro';
import { Platform } from 'ionic-angular';

Then, via the constructor we pulled in the Platform and AdMobPro:

constructor(public navCtrl: NavController, private alertCtrl: AlertController, private admob: AdMobPro, private platform: Platform) { }

Then we wrapped everything in the platform.ready() promise. This is the most important part of the code! If you wouldn’t do that, it could happen that your app would start up and the plugins would still not be properly set up, and you wouldn’t see the ads displayed.

But then again, sometimes you would, and this is what it would make it a nightmare to debug. This is a very common issue that I’ve seen even back from Ionic 1 when answering the questions on StackOverflow. So, you may want to keep an ?️ on the fact that you need to wrap any plugin calls inside the platform.ready() promise, as that way you’ll be sure that all of the plugins have loaded before you’ll use them.

The code that’s executed after the promise resolves sets up our admobid object with banner and interstitial properties. Then we’re calling the createBanner and prepareInterstitial functions on the injected admob object. Note that the banner is set to show automatically when the app loads (autoShow: true) and the interstitial isn’t. Also, note that we’ve set the position of the banner ad to the bottom:

this.platform.ready().then(() => {
    var admobid = {
        banner: 'ca-app-pub-7957971173858308/5068937357',
        interstitial: 'ca-app-pub-7957971173858308/5667703151'
    };

    this.admob.createBanner({
        adId: admobid.banner,
        isTesting: true,
        autoShow: true,
        position: this.admob.AD_POSITION.BOTTOM_CENTER
    })

    this.admob.prepareInterstitial({
        adId: admobid.interstitial,
        isTesting: true,
        autoShow: false
    })
});

Then we added the showshowInterstitialAdAd function, which shows the Interstitial ad:

showInterstitialAd() {
    if (AdMobPro) {
        this.admob.showInterstitial();
    }
}

Of course, at this point, change the adId variable to your admob_key which you obtained in the first part (step 9). Also, when you’ll be publishing your app, don’t forget to change the isTesting variable to false. Don’t worry, I’ll remind you when we get to that part.

? If you run into any problems with this, just ping in the comments, and I’ll do my best to help you.

One common thing that you might have to do for Android is to install some extras via the Android SDK manager. To do so open Android Studio and select Configure->SDK Manager:

Make sure you have installed the packages marked as Installed on the image below (usually, those are Google Billing Library and Google Play services):

For more information about the Android SDK manager, take a look at the section about How to test our application on the real physical devices and emulators futher in the post.

What kind of an ad should you show?

This plugin’s documentation states an interesting fact that it’s strongly recommended to use the Interstitial ad type because it brings more than 10 times profit than the banner Ad. Here’s the table from the official documentation:

Ad Format Banner Interstitial
Click Rate < 1% 3-15%
RPM (1k impressions) 0.5$ – 4$ 10-50$

Banner ad is the small add that is usually placed in the bottom of the screen, whereas Interstitial ads are full-screen ads that cover the interface of their host app. Therefore, you may rather want to opt for this kind of an ad instead for the Banner one.

It’s important to note that there’s probably no exact formula here on when to show the Interstitial Ad, but there are some best practices, and this is what Google has to say about it:

Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, like sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it’s easy to present an interstitial without disrupting their experience. Make sure you consider at which points in your app’s workflow you’ll display interstitials, and how the user is likely to respond.

You can learn a bit more about it here.

Anyways, as you saw in my demo code above, I’ve opted for showing the banner ad all the time in the bottom of the screen, and I’m showing the interstitial ad every 5th time the user clicks the = button. You can tweak this any way you like in your app, but please remember the points mentioned above about best practices.

How to use Ionic.io cloud service to share our application with other users without going through the app store

Having the ability to immediately get feedback on something that you’re working on, without having to install the app manually on your client’s devices or waiting for the App Store/Play Store approval is indispensable for constant feedback loop which is crucial in rapid application development. This is something that Eric Ries stresses a lot in his book The Lean Startup.

In Ionic, this is easier than you may have thought. All you have to do is create the account on https://apps.ionic.io and after that in your Terminal/Command prompt in the root of the project just type the following command:

ionic upload

This will prompt you to login with your username and password combination which you created in the previous step. After successful login, the app will be uploaded to the Ionic.io cloud service and you will be able to view the app through an app called Ionic View, which you can download for free on your smartphone from the App Store/Play Store.

The output of the above command is short:

[INFO] Running app-scripts build: 

[09:55:39]  build dev started ... 
[09:55:39]  clean started ... 
[09:55:39]  clean finished in 2 ms 
[09:55:39]  copy started ... 
[09:55:39]  transpile started ... 
[09:55:42]  transpile finished in 2.30 s 
[09:55:42]  preprocess started ... 
[09:55:42]  deeplinks started ... 
[09:55:42]  deeplinks finished in 4 ms 
[09:55:42]  preprocess finished in 5 ms 
[09:55:42]  webpack started ... 
[09:55:42]  copy finished in 2.44 s 
[09:55:47]  webpack finished in 5.10 s 
[09:55:47]  sass started ... 
[09:55:48]  sass finished in 1.39 s 
[09:55:48]  postprocess started ... 
[09:55:48]  postprocess finished in 4 ms 
[09:55:48]  lint started ... 
[09:55:48]  build dev finished in 8.84 s 
> ionic cordova prepare
> cordova prepare
✔ Running command - done!

[09:55:50]  lint finished in 1.87 s 
✔ Requesting snapshot upload - done!
✔ Uploading snapshot - done!
[OK] Uploaded snapshot 19a5c87e-92aa-4757-b2c0-1c24e7ee9657!

And, as stated in the output, to share your app with a client or a friend, without first having to go through the App Store/Play Store, go to https://apps.ionic.io and add the testers email under the Settings->Collaborators section:

User will receive an email which will guide him through the setup:

⚠️ Those of you coming from Ionic 1 and being used to the ionic share EMAIL command, you’ll get the following error message if you run it:
ionic share [email protected]

[ERROR] ionic share has been removed as of CLI 3.0.
The functionality now exists in the Ionic Dashboard: https://apps.ionic.io

If you’ll get an error like this:

[ERROR] Your project file (./ionic.config.json) does not contain ‘app_id’. Run ionic link.

Then execute the command ionic link and choose the Create new app option in the terminal. That will bring you to the web interface where you have to enter the name of your app and click the Create App button:

Once the app is created you’ll see something like this:

Now go back to your Terminal and run ionic link again and choose the name your app. You should see an output similar to this:

✔ Looking up your apps - done!
? Which app would you like to link SuperSimpleCalculator (dec5230f)
> ionic config set app_id dec5230f
[OK] app_id set to dec5230f in ./ionic.config.json!
[OK] Project linked with app dec5230f!

Now you can rerun the ionic upload command and get an output that the snapshot of your app has been uploaded.

Once your client/tester/friend gets the email for being a Collaborator, he will be guided through setting up Ionic View and viewing your app.

However, there’s one more way for your client/friend to try out the app. First, tell them to download the Ionic View app from the App Store/Play Store:

They will have to sign up (it’s free):

And once they’re logged in, they have to click the PREVIEW A SHARED APP button:

At this point, they will have to enter your App Id which you’ll have to send them (Slack, Email, Messenger, choose your ?). You can find your id in the Ionic dashboard. In my case the id is dec523f:

They have to enter this id in the form and click the LOAD APP button:

They will get the following screen with instructions on how to use the app:

You will notice that we will not see ads in this version because Ionic View does not support the AdMob plugin:

Suffice to say; you dear reader can also try this out via your own Ionic View app.

How to test our application on the real physical devices and emulators

If you run the application (to which you added AdMob) in the browser, you will see few notices in your browser’s Console output that AdMob is not defined:

Also, if you view the app in Ionic View, you will notice that no ads will show up. This is because Cordova plugins don’t work in the browser, nor in the Ionic View. Instead, they have to be tested on the real device or in an emulator (in iOS terminology the word simulator is used). Just for reference, there are some plugins that work in the Ionic View.

In this section, we’re going to show how to install the needed prerequisites and how to run our application in an simulator/emulator and on the actual physical device for both iOS and Android.

iOS settings

The main tool for developing native iOS applications is Xcode. Xcode is praise-worthily free for download, and it comes with a lot of simulators in which you can see how your app would look like on a real device.

However, if you want to build and deploy iOS applications to the App Store, you need to have a Mac computer since Xcode only works on their operating system. Yes, even if you’re using Ionic, you need to use Xcode to build the application for iOS.

There are some ways around this, like for example with using a so-called Hackintosh computer, but honestly, from my experience, this is just not worth it.

If you’re really anti-Apple ?, then you’ll be happy to know that there are services which allow you to rent a Mac in the cloud, just for the time you need to build your application. Also, Ionic offers the so-called Package service that allows you to build mobile apps for any supported platform even if you don’t have a Mac. We won’t cover that here, but you can take a look at the official Package service documentation.

To publish an app in the App Store (or test it on your own iOS device) you’ll need to purchase the Apple Developer Program license which costs US $99 per year. You’ll need to sign up at http://developer.apple.com, but don’t worry about this for now; we’ll cover all the steps in the next tutorial where I’ll guide you through the process of deploying the application for both the Apple’s App Store and Google’s Play Store.

Installing the needed tools

As we’ve mentioned before, you need to install Xcode, and you can do that by opening up the App Store application on your Mac and search for Xcode. You install it like any other application by clicking on the download button and following the NextNextNext type of installation.

After the installation is finished, open up Xcode, and navigate to Xcode -> Preferences -> Downloads tab. Here you can download the latest version of the Simulator available. In my case, at the time of this writing, the latest version is iOS 11.0 Simulator, as you can see on the image below:

Also, we need to install the ios-sim package with npm:

npm install -g ios-sim

Running our application in a simulator

Now, to test our application in a simulator all we have to do is execute the following command:

ionic cordova emulate ios

After a bunch of cryptic messages you should see a Xcode simulator open up and show your awesome application along with a splash screen and ads:

⚠️ In case you get an error like this:

** BUILD SUCCEEDED **
Error: Cannot read property 'replace' of undefined
[ERROR] An error occurred while running cordova emulate ios (exit code 1).

Then execute the following command (don’t use sudo if on Windows):

cd platforms/ios/cordova/node_modules/ && sudo npm install ios-sim@latest

After this repeat the emulate command and all should be well.

Of course, run the ionic cordova emulate ios command in the root directory of the project, not in the /platforms/ios/cordova/node_modules folder!

If you test the app by doing five calculations, then after the fifth time you press the equals button = the Interstitial ad will appear, as shown in the image below:

If you exit the simulator back to the home screen (by pressing `Command (⌘) + Shift + H) you will see the application’s icon:

When you’re testing your application in a browser with ionic lab you have that great live reload feature. You can have that too in the simulator if you run the simulator with the extra -l flag. If you also want to see the console.log output, as you would see it in the browser, then you have to add the –c flag:

ionic cordova emulate ios -lc

Since we need to have an Apple Developer account to run the application on our physical phone device, we will leave this for our next tutorial where we’ll also show how to deploy the application to the actual App Store.

⚠️ At the time of writing this you can see in the updated screenshots of the iOS 11 simulator, the app isn’t iOS 11 ready. However, anyone that will be following this tutorial anew and will have ionic and cordova npm packages up to date, will not have this problem, as the Ionic team fixed everything in time for the iPhone X release. For more information, see the official blog post. For those of you who are maybe looking to update your Ionic 1 app to look nice on iPhone X, take a look at this tutorial.

Android settings

There are no prerequisites for Android development regarding the operating systems; you can develop for Android on Mac, Linux, and Windows computers.

Android provides some tools for developers that are available for free from their website.

? To publish an app in the Play Store you’ll need to purchase the Developer Program license which costs only US $25 one-time fee. You’ll need to sign up at https://play.google.com/apps/publish/signup/, but as said before – don’t worry; we’ll cover all the steps in the next tutorial.

Installing the needed tools

Download Android Studio from https://developer.android.com/studio/index.html

The installation is a simple NextNextNext type of installation, but if you get stuck, they have great official documentation.

Next, you need to set up the so-called PATH variable to point to the Android SDK tools. You can find the path by opening up the Android Studio, select the Configure->SDK Manager option and copy the Android SDK Location:

On Mac, you can set the PATH variable like this:

export PATH=$PATH:/Users/nikola/Library/Android/sdk/tools/.

You may want to put this line to your .bash_profile (or any related that you may have like .zshrc) file. For any further details about how to set the PATH variable, you can take a look at this tutorial.

As for Windows, the command would be:

set PATH=%PATH%;C:\Dev\android-sdk\tools

⚠️ To be honest, you may still encounter some errors while trying to get this to work and I’ve answered quite a few issues on StackOverflow. So, if you get stuck at this point, just drop me a line in the comments, and I’ll do my best to help.

Once you’ve set the PATH variable correctly for your operating system, you can check if it’s OK by opening up your Terminal/Command prompt and typing:

android

You should get an output similar to this one:

android
*************************************************************************
The "android" command is deprecated.
For manual SDK, AVD, and project management, please use Android Studio.
For command-line tools, use tools/bin/sdkmanager and tools/bin/avdmanager
*************************************************************************
Invalid or unsupported command ""

Supported commands are:
android list target
android list avd
android list device
android create avd
android move avd
android delete avd
android list sdk
android update sdk

You may get a message that you don’t have java tools installed:

In that case, click the More Info... button and you’ll be directed to their website where you have to click on the DOWNLOAD button (make sure you click the JDK one): Then, on the next screen, click the Accept License Agreement and select your operating system:

After the download run the .dmg file (on Mac OS) and finish the NextNextNext type of installation. If you’re on Windows, make appropriate choices for your OS.

Finally, you need to set up the SDK packages. For those of you who are in this field a bit longer, you’ll remember that you had to do everything via the Terminal/Command prompt. Specifically, for this you had to enter:

android sdk

But, with the new version of the Android Studio, as you saw in the previous Terminal output, you don’t have to do that. The way you should open up the SDK Manager is by opening up Android Studio and then click on Configure->SDK Manager:

I recommend that you download just the most recent packages as shown on the image below. Most probably you’ll have everything installed except Google Play services and Google Play Billing Library.

Make sure that you download only the platforms that you’ll need. On the image below, only the Android 7.1.1 (Nougat) version is installed:

Now run ionic cordova build android, and open the folder platforms/android/ with Android Studio (click the Open an existing Android Studio project link/button) and you should see something like this:

Create a new emulator

You need to have an emulator on which you’ll run your Android app. To begin the process of adding it, click on the Tools->Android->AVD Manager:

Click the Create Virtual Device button:

Choose a device:

Select the system image and click the Next button. If need be, first click on the Download link.

On the final screen just click the Finish button and you should see the following screen which shows the summary of your virtual devices:

Run the app on the new emulator

Run ionic cordova emulate android and you should see an Android emulator start up and show you your app:

Run the app on the physical device

If you would like to run the application on your own Android device then you first have to run the following command to build the project:

ionic cordova build android

The last few lines of the output will be something like:

BUILD SUCCESSFUL

Total time: 1.557 secs
Built the following apk(s): 
    /Users/nikola/DEV/Ionic3/Ionic3_3rdTutorial/platforms/android/build/outputs/apk/android-debug.apk

To be able to test your application on your Android device, you have to enable the developer settings, and you can do that in few steps:

  • Open the Settings view and scroll to About Phone
  • At the bottom of the About Phone view find a Build Number and tap on it seven times to enable the developer mode.
  • After this you can go back to the Settings view, and you’ll see a new option called Developer Options

Now you have to enable the USB debugging, and you can do that in the next few steps:

  • Select Developer Options item in the Settings view
  • Scroll down until you see the USB debugging option
  • Toggle it ON
  • Now your device is set up for debugging, and when it’s connected to your computer you’ll be able to deploy the application to the device

Now connect your device and execute the following command in your Termina/Command prompt:

ionic cordova run android

Find the application in your application list and open it. You should see the ads at the bottom, and after the fifth calculation, you should see an Interstitial ad appear.

⚠️ If for some reason the ionic cordova run android command wouldn’t work for you, you can always just copy the generated .apk file manually to your connected device (for example in the Downloads folder). After that open the Downloads folder on your phone with the file manager application that you use and open the .apk file that you pasted in. This way you’ll be prompted to install the application on your phone and then you’ll be able to find it in the programs list:

Conclusion

In this tutorial, you’ve learned quite a few things. You learned how to polish the existing calculator application by improving the design and user experience. Next, you learned how to create icons and splash screen images automatically. Then, how to make money with your application by using Google AdMob ads. Also, how to share your application with other users without going through the app stores. Finally, you learned how to test your application on the real physical devices and emulators.

In the next tutorial, I’m going to show you how to prepare the application for the Apple’s App Store and Google’s Play Store and finally, how to publish the application to both Apple’s App Store and Google’s Play Store.

Until next time, keep on coding ✌️

How to polish our existing @ionicframework 3 calculator application https://t.co/uBmiwsyHps

— Nikola Brežnjak (@HitmanHR) December 15, 2017

Ionic3

How to create icons and splash screen images automatically in Ionic framework 3

⚠️ In case you’re looking for how to create icons and splash screen images automatically in Ionic framework version 1, then you can check out this post. For more Ionic framework 3 posts check out the step by step info on How to get started with Ionic framework 3 on Windows and Mac.

TL;DR

Just execute ionic cordova resources command in your Ionic 3 project root folder.

!TL;DR

The icon is an important part of your application because it represents your application’s brand, and it helps to identify quickly where the app is on your phone. In case you’re familiar with creating apps then you will remember that it is a tedious process to create a lot of different size images both for iOS and Android platforms.

Also, the same goes for the so-called splash screen that shows up every time the application starts. Although having a splash screen is not mandatory, it certainly adds up to the feeling of a complete and professional application, which one would certainly want to convey with his application.

Ionic helps tremendously with this by providing a single Ionic CLI command to generate all the needed icon and splash screen sizes for us automatically. Also, Ionic created Photoshop Splash Screen Template, which you can download for free and use as a guideline for creating an icon. However, if you create you project by using ionic start command, as we have, then you’ll already have both the icon.png and splash.png files in the resources folder, and you can just edit them.

For when you’re creating a branded product having a custom made icon is definitely a must. However, in this case, I’ll show you how to use one of the free services to search for a free icon which you can then use in your application (even if your application is a commercial application).

I tend to use IconFinder a lot, and here are the settings which you have to use to filter out the calculator images that are Free (PRICE) and can be used in commercial applications and that don’t even require a link back (LICENSE TYPE).

Of course, you can also choose to buy an image if you happen to find one that you like. You can additionally search by format, size, and background. The filters should look like this (or use this prepared link which sets them automatically):

I’m going to use the last one in the first row. Simply click on it, and you should get to the download page that looks like this:

To download it just click on the green ‘Download PNG’ button.

Now, in the resources folder find and open the icon.png file with an image editor of your choice. I’m going to use Gimp in this example as it’s free cross-platform image editor available for all the major operating systems (Linux, OS X, Windows). You should see something like this:

Now we need to do a few steps:

  • select the whole area (Ctrl + a or Command + a) and press the DEL button on your keyboard. This should leave you with a blank white canvas.
  • drag the calculator icon on this white canvas and you should see something like this:
  • click on the scale tool
  • then click on the calculator image. You should get this popup:
  • change the values in the popup to 1024px for both Width and Height and click the Scale button.
  • click on the Alignment Tool, then click on the calculator image and then on the circled two buttons on the image below. This will align the calculator image horizontally and vertically

Now save the file by going to File->Overwrite icon.png:

Repeat the process to create the splash screen image and name it (overwrite it as) splash.png. The image I came up with looks like this:

Now that you have both icon.png and splash.png images ready navigate with your Terminal/Command prompt to the root folder of the application and run the following command:

ionic cordova resources

If at this point you get an error like this:

[ERROR] No platforms have been added. Please run: ionic cordova platform add

That means that you haven’t added any platforms yet to which Ionic should build. Since we’re going to build the app for both Apple Store and Android Play Store we’re going to use the following two commands:

ionic cordova platform add android
ionic cordova platform add ios

You should see an output similar to this:

ionic cordova platform add ios
> cordova platform add ios --save
✔ Running command - done!
Using cordova-fetch for cordova-ios@~4.4.0
Adding ios project...
Creating Cordova project for the iOS platform:
    Path: platforms/ios
    Package: io.ionic.starter
    Name: MyApp
iOS project created with [email protected]
Discovered plugin "cordova-plugin-console" in config.xml. Adding it to the project
Installing "cordova-plugin-console" for ios
Adding cordova-plugin-console to package.json
Saved plugin info for "cordova-plugin-console" to config.xml
Discovered plugin "cordova-plugin-device" in config.xml. Adding it to the project
Installing "cordova-plugin-device" for ios
Adding cordova-plugin-device to package.json
Saved plugin info for "cordova-plugin-device" to config.xml
Discovered plugin "cordova-plugin-splashscreen" in config.xml. Adding it to the project
Installing "cordova-plugin-splashscreen" for ios
Adding cordova-plugin-splashscreen to package.json
Saved plugin info for "cordova-plugin-splashscreen" to config.xml
Discovered plugin "cordova-plugin-statusbar" in config.xml. Adding it to the project
Installing "cordova-plugin-statusbar" for ios
Adding cordova-plugin-statusbar to package.json
Saved plugin info for "cordova-plugin-statusbar" to config.xml
Discovered plugin "cordova-plugin-whitelist" in config.xml. Adding it to the project
Installing "cordova-plugin-whitelist" for ios
Adding cordova-plugin-whitelist to package.json
Saved plugin info for "cordova-plugin-whitelist" to config.xml
Discovered plugin "ionic-plugin-keyboard" in config.xml. Adding it to the project
Installing "ionic-plugin-keyboard" for ios
Adding ionic-plugin-keyboard to package.json
Saved plugin info for "ionic-plugin-keyboard" to config.xml
--save flag or autosave detected
Saving ios@~4.4.0 into config.xml file ...
✔ Copying default image resources into ./resources/ios - done!

> cordova platform add android --save
✔ Running command - done!
Using cordova-fetch for cordova-android@~6.2.2
Adding android project...
Creating Cordova project for the Android platform:
    Path: platforms/android
    Package: io.ionic.starter
    Name: MyApp
    Activity: MainActivity
    Android target: android-25
Subproject Path: CordovaLib
Android project created with [email protected]
Installing "cordova-plugin-console" for android
Installing "cordova-plugin-device" for android
Installing "cordova-plugin-splashscreen" for android
Installing "cordova-plugin-statusbar" for android
Installing "cordova-plugin-whitelist" for android

               This plugin is only applicable for versions of cordova-android greater than 4.0. If you have a previous platform version, you do *not* need this plugin since the whitelist will be built in.

Installing "ionic-plugin-keyboard" for android
--save flag or autosave detected
Saving android@~6.2.3 into config.xml file ...
✔ Copying default image resources into ./resources/android - done!

After this, you can safely run the ionic cordova resources command, and you should get the following output:

✔ Collecting resource configuration and source images - done!
✔ Filtering out image resources that do not need regeneration - done!
✔ Uploading source images to prepare for transformations - done!
✔ Generating platform resources: 48 / 48 complete - done!
✔ Modifying config.xml to add new image resources - done!

From the output, you can see that 48 images were created and hopefully now you realize how much time this saved. All the needed configuration regarding the icons and splash screens was generated by Ionic and placed in the config.xml file.

It’s worth noting that you will not see the icon nor the splash screen when using the browser testing or Ionic View testing. Instead, you will only see these once you deploy them to the actual physical device or the emulator.

⚠️ You can add an iOS platform if you’re developing on a Windows machine, and ionic cordova resources command will generate icons and splash screens for it. However, keep in mind that you will not be able to build the project for iOS on your Windows machine. Instead, you’ll need a Mac computer to do so.

How to create icons and splash screen images automatically in Ionic framework 3 @ionicframework https://t.co/EKe3QDeo8E

— Nikola Brežnjak (@HitmanHR) August 23, 2017

Ionic3

How to make money with Google AdMob ads in Ionic framework 3

In case you’re looking for a way to implement Google AdMob ads in Ionic framework 1, then check out this tutorial: Adding AdMob to Ionic framework application step by step.

Introduction

There are multiple ways you can earn money with your app these days and here are just a few of them:

  • Paid app – set a price for your app directly on the App/Play Store that users need to pay before downloading your app
  • Freemium – give the app for free but charge for in-app purchases like adding some extra features (think more gold or faster production in game apps)
  • Ad-based – show ads inside your application. Potentially offer the in-app purchase to remove the ads

In this post, I’m going to cover the Ad-based monetization option, and I’ll show you how to add Google AdMob ads to a simple Ionic 3 blank template application. There are two parts to implementing Google AdMob ads to an Ionic project and I broke them into: AdMob settings and Ionic settings.

Demo app and repo

You can check the final code on Github. When you clone it, run npm install inside the project. In case you have your development machine set up for Ionic, then you can run the project with ionic emulate ios or ionic emulate android. If you don’t but would like to, see this post on How to get started with Ionic framework 3 on Mac and Windows.

You should see something like this in your simulator/emulator:

AdMob settings

Let’s start with AdMob settings:

  1. Sign in/Sign up for AdMob at https://www.google.com/admob/
  2. Click the Apps and then ADD APP button:

  1. Since our app is not published yet we will click the No button:

  1. Fill in the app name and platform and click the ADD button:

  1. Save the App ID somewhere and proceed to create the Ad unit

  1. Select Banner Ad format:

  1. Configure the adds type, size, placement, style, name:

  1. You can read additional info on how to implement GA and AdMob, but for now let’s just click Done:

  1. You will now see the following similar screen:

The most important thing to note here is this Ad unit ID, which in my test case is ca-app-pub-7957971173858308/5068937357. Make a note of this string as it’s the most important part of this setting. You can click on the copy to clipboard button and paste it as a comment (for now) in your app.

  1. Create as much Ad units as you may need (for each platform[iOS, Android] and ad format [Banner, Interstitial, etc.]). In my case, I just created the additional Interstitial Ad and will use them on both iOS and Android devices for the purpose of this demo.

Ionic settings

Those of you familiar with Ionic 1 know that you can add any plugin to your Ionic project thanks to the project called ngCordova. For Ionic 3, there’s the same thing called Ionic Native.

Ionic Native is a TypeScript wrapper for Cordova/PhoneGap plugins that makes it easy to add any native functionality that you may need into your Ionic app. Ionic Native wraps the plugin callbacks in a Promise or an Observable, providing a common interface for all plugins and ensuring that native events trigger change detection in Angular.

First, let’s start an empty Ionic 3 application based on the blank template:

ionic start Ionic3AdMobTest blank --cordova

You should see the following output:

✔ Creating directory ./Ionic3AdMobTest - done!
[INFO] Fetching app base (https://github.com/ionic-team/ionic2-app-base/archive/master.tar.gz)
✔ Downloading - done!
[INFO] Fetching starter template blank (https://github.com/ionic-team/ionic2-starter-blank/archive/master.tar.gz)
✔ Downloading - done!
✔ Updating package.json with app details - done!
✔ Creating configuration file ionic.config.json - done!
[INFO] Installing dependencies may take several minutes!
> npm install
✔ Running command - done!
> npm install --save-dev --save-exact ionic@latest
✔ Running command - done!
> npm install --save-dev --save-exact @ionic/cli-plugin-ionic-angular@latest
✔ Running command - done!
> npm install --save-dev --save-exact @ionic/cli-plugin-cordova@latest
✔ Running command - done!
> npm dedupe
✔ Running command - done!
> git init
✔ Running command - done!
> git add -A
✔ Running command - done!
> git commit -m "Initial commit" --no-gpg-sign
✔ Running command - done!

♬ ♫ ♬ ♫  Your Ionic app is ready to go! ♬ ♫ ♬ ♫

Run your app in the browser (great for initial development):
  ionic serve

Run on a device or simulator:
  ionic cordova run ios

Test and share your app on a device with the Ionic View app:
  http://view.ionic.io


Next Steps:
Go to your newly created project: cd ./Ionic3AdMobTest

Navigate to the root of the application with your Terminal/Command prompt and execute the following command to add the cordova-plugin-admobpro plugin:

ionic cordova plugin add cordova-plugin-admobpro

You should see the following output after running the command:

✔ Running command - done!
Adding cordova-plugin-admobpro to package.json
Saved plugin info for "cordova-plugin-admobpro" to config.xml

Additionally, you will also need to run this command:

npm install --save @ionic-native/admob-pro

which, if completed successfully, will only output something like added 1 package in 3.331s to the console.

You need to add this second command as well because this installs some files needed by TypeScript.

⚠️ At this point, depending on the version of Ionic CLI that you have you may need to add a platform by executing: ionic cordova platform add ios or ionic cordova platform add android depending on the platform you’re trying to build for. You have to execute that if the command ionic cordova platform ls shows that you don’t have any installed platforms on the current project:

→ ionic cordova platform ls
✔ cordova platform ls - done!
Installed platforms:
Available platforms: 
 android ~6.2.2
 blackberry10 ~3.8.0 (deprecated)
 browser ~4.1.0
 ios 4.4.0
 osx ~4.0.1
 webos ~3.7.0

If everything is fine with running ionic cordova platform add ios you will see an output like this:

Using cordova-fetch for cordova-ios@~4.4.0
Adding ios project...
Creating Cordova project for the iOS platform:
    Path: platforms/ios
    Package: io.ionic.starter
    Name: MyApp
iOS project created with [email protected]
Installing "cordova-plugin-admobpro" for ios
Installing "cordova-plugin-extension" for ios
Discovered plugin "cordova-plugin-console" in config.xml. Adding it to > the project
Installing "cordova-plugin-console" for ios
Adding cordova-plugin-console to package.json
Saved plugin info for "cordova-plugin-console" to config.xml
Discovered plugin "cordova-plugin-device" in config.xml. Adding it to > the project
Installing "cordova-plugin-device" for ios
Adding cordova-plugin-device to package.json
Saved plugin info for "cordova-plugin-device" to config.xml
Discovered plugin "cordova-plugin-splashscreen" in config.xml. Adding > it to the project
Installing "cordova-plugin-splashscreen" for ios
Adding cordova-plugin-splashscreen to package.json
Saved plugin info for "cordova-plugin-splashscreen" to config.xml
Discovered plugin "cordova-plugin-statusbar" in config.xml. Adding it > to the project
Installing "cordova-plugin-statusbar" for ios
Adding cordova-plugin-statusbar to package.json
Saved plugin info for "cordova-plugin-statusbar" to config.xml
Discovered plugin "cordova-plugin-whitelist" in config.xml. Adding it > to the project
Installing "cordova-plugin-whitelist" for ios
Adding cordova-plugin-whitelist to package.json
Saved plugin info for "cordova-plugin-whitelist" to config.xml
Discovered plugin "ionic-plugin-keyboard" in config.xml. Adding it to > the project
Installing "ionic-plugin-keyboard" for ios
Adding ionic-plugin-keyboard to package.json
Saved plugin info for "ionic-plugin-keyboard" to config.xml
--save flag or autosave detected
Saving ios@~4.4.0 into config.xml file ...
✔ Copying default image resources into ./resources/ios - done!

Btw, there is also a free version of the AdMob Pro plugin. But, honestly, if you really start making money with your app, this will be a minor expense. Besides, if you’re having problems giving back to the actual plugin through which you’re making money then my dear padawan you have yet much to learn…

Now, let’s add this plugin to our app’s NgModule. In the src/app/app.module.ts file import AdmobPro:

import { AdMobPro } from '@ionic-native/admob-pro';

and then add it to the Providers array. The whole contents of the src/app/app.module.ts file should now looks like this:

import { BrowserModule } from '@angular/platform-browser';
import { ErrorHandler, NgModule } from '@angular/core';
import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
import { SplashScreen } from '@ionic-native/splash-screen';
import { StatusBar } from '@ionic-native/status-bar';

import { AdMobPro } from '@ionic-native/admob-pro';

import { MyApp } from './app.component';
import { HomePage } from '../pages/home/home';

@NgModule({
    declarations: [
        MyApp,
        HomePage
    ],
    imports: [
        BrowserModule,
        IonicModule.forRoot(MyApp)
    ],
    bootstrap: [IonicApp],
    entryComponents: [
        MyApp,
        HomePage
    ],
    providers: [
        StatusBar,
        SplashScreen,
        AdMobPro,
        { provide: ErrorHandler, useClass: IonicErrorHandler }
    ]
})
export class AppModule { }

Now I’m going to show you the final content of the src/pages/home/home.ts file and will explain what was changed step by step:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

import { AdMobPro } from '@ionic-native/admob-pro';
import { Platform } from 'ionic-angular';

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {
    constructor(public navCtrl: NavController, platform: Platform, private admob: AdMobPro) {
        platform.ready().then(() => {
            var admobid = {
                banner: 'ca-app-pub-7957971173858308/5068937357',
                interstitial: 'ca-app-pub-7957971173858308/5667703151'
            };

            this.admob.createBanner({
                adId: admobid.banner,
                isTesting: true,
                autoShow: true,
                position: this.admob.AD_POSITION.BOTTOM_CENTER
            })

            this.admob.prepareInterstitial({
                adId: admobid.interstitial,
                isTesting: true,
                autoShow: false
            })
        });
    }

    showInterstitialAd() {
        if (AdMobPro) {
            this.admob.showInterstitial();
        }
    }
}

First, we added the imports:

import { AdMobPro } from '@ionic-native/admob-pro';
import { Platform } from 'ionic-angular';

Then, via the constructor we injected Platform and AdMobPro:

constructor(public navCtrl: NavController, platform: Platform, private admob: AdMobPro)

Then we wrapped everything in the platform.ready() promise. This is the most important part of the code! If you wouldn’t do that, it could happen that your app would start up and the plugins would still not be properly set up, and you wouldn’t see the ads displayed.

But then again, sometimes you would, and this is what it would make it a nightmare to debug. This is a very common issue that I’ve seen even back from Ionic 1 when answering the questions on StackOverflow. So, you may want to keep an ?️ on the fact that you need to wrap any plugin calls inside the platform.ready() promise, as that way you’ll be sure that all of the plugins have loaded before you’ll use them.

The code that’s executed after the promise resolves sets up our admobid object with banner and interstitial properties. Then we’re calling the createBanner and prepareInterstitial functions on the injected admob object. Note how the banner is set to show automatically when the app loads (autoShow: true) and the interstitial isn’t. Also, note how we’ve set the position of the banner ad to the bottom:

platform.ready().then(() => {
    var admobid = {
        banner: 'ca-app-pub-7957971173858308/5068937357',
        interstitial: 'ca-app-pub-7957971173858308/5667703151'
    };

    this.admob.createBanner({
        adId: admobid.banner,
        isTesting: true,
        autoShow: true,
        position: this.admob.AD_POSITION.BOTTOM_CENTER
    })

    this.admob.prepareInterstitial({
        adId: admobid.interstitial,
        isTesting: true,
        autoShow: false
    })
});

Then we added the showshowInterstitialAdAd function, which shows the Interstitial ad:

showInterstitialAd() {
    if (AdMobPro) {
        this.admob.showInterstitial();
    }
}

Of course, at this point, change the admobid object properties to your AdMob keys which you obtained in the first part (step 9).

? If you run into any problems with this, just ping in the comments, and I’ll do my best to help you.

One common thing that you might have to do for Android is to install some extras via the Android SDK manager. To do so open Android Studio and select Configure->SDK Manager:

Make sure you have installed the packages marked as Installed on the image below (usually, those are Google Billing Library and Google Play services):

What kind of an ad should you show?

This plugin’s documentation states an interesting fact that it’s strongly recommended to use the Interstitial ad type because it brings more than 10 times profit than the banner Ad. Here’s the table from the official documentation:

Ad Format Banner Interstitial
Click Rate < 1% 3-15%
RPM (1k impressions) 0.5$ – 4$ 10-50$

Banner ad is the small add that is usually placed in the bottom of the screen, whereas Interstitial ads are full-screen ads that cover the interface of their host app. Therefore, you may rather want to opt for this kind of an ad instead for the Banner one.

It’s important to note that there’s probably no exact formula here on when to show the Interstitial Ad, but there are some best practices, and this is what Google has to say about it:

Interstitial ads work best in apps with natural transition points. The conclusion of a task within an app, like sharing an image or completing a game level, creates such a point. Because the user is expecting a break in the action, it’s easy to present an interstitial without disrupting their experience. Make sure you consider at which points in your app’s workflow you’ll display interstitials, and how the user is likely to respond.

You can learn a bit more about it here.

Anyways, as you saw in our demo code above, we opted for showing the banner ad all the time in the bottom of the screen, and we’re showing the interstitial ad when we click the button. You can tweak this any way you like in your app, but please remember the points mentioned above about best practices.

Finally, the view template

Replace the src/pages/home/home.html file content with this:

<ion-header>
    <ion-navbar>
        <ion-title>
            Ionic Blank
        </ion-title>
    </ion-navbar>
</ion-header>

<ion-content padding>
    <button ion-button (click)="showInterstitialAd()">Show the interstitial Ad</button>
</ion-content>

Clicking the Show the interstitial Ad button will call the showInterstitialAd() function which will show the interstitial as shown in a gif at the beginning of this tutorial.

Let’s test this

Run ionic cordova emulate ios and in a few seconds your simulator should start up and show you this:

There are few things that could go wrong with this, so for example if you get an error like this:

Error: Cannot read property 'replace' of undefined

[ERROR] Cordova encountered an error.
        You may get more insight by running the Cordova command above directly.

[ERROR] An error occurred while running cordova run ios (exit code 1).

Then you can try the solution from this StackOverflow post: Execute the following command in the platforms/ios/cordova/node_modules folder: sudo npm install ios-sim@lates.

If you get an error telling you that it can’t open up the simulator, then you may want to try running the build command: ionic cordova build ios and after that open the MyApp.xcworkspace file from the platforms/ios folder:

Select the simulator device that you’d like to run your app on and click the run button from your Xcode:

If you run into any other problems while trying to run this, let’s try to solve them in the comments and thus help others that may have the same issues as well ?

Conclusion

In this post, we’ve shown how easy it is to add monetization options to your app. Now it’s ‘just’ on you to actually make an app that will be used a lot of times and whose users will want to click on the ads. ?

Till next time, ✌️

How to make #money with Google #AdMob ads in #Ionic framework 3 https://t.co/In5UPrLTyn

— Nikola Brežnjak (@HitmanHR) August 16, 2017

Ionic3

How to create a calculator application with Ionic framework 3 by using Ionic Creator for UI

This is the second post in a series of posts which will teach you how to take advantage of your web development knowledge in building hybrid applications for iOS and Android. The first post in this series was all about How to get started with Ionic Framework 3 on Windows and Mac.

This second post explains:

  • How to create a calculator interface mockup
  • How to create a calculator interface prototype without coding by using Ionic Creator
  • How to start the Ionic 3 application based on the created interface
  • Which are the most important folders and files and what is the starting point of the Ionic 3 application
  • How to create the calculator logic

Finished project:

  • clone the code from Github
  • in the project directory execute ionic lab to run the project locally in your browser
  • you can check out the live example of this application or view this gif:

Introduction

Since there are not so many Calculator applications in the App Store, who knows, you just may create a bestseller in this category, if you add a needed tweak or two.

All jokes and hopes aside; this seemed to be decent, but still easy to accomplish task. Let’s start this chapter by creating the interface for our application.

Calculator interface mockup

Before starting any application, we should know what we want (well, at least in general). We should know what problem are we trying to solve with our application and how are we going to solve it. Also, we should have a decent idea of how we would want our application to look like.

The answers to the first two questions would be rather easy; the problem is that we can’t do calculations fast enough in our mind (well, except if you’re Arthur Benjamin) and we need a tool to help us with that. Surely, there are specific calculator devices, but it would be too cumbersome to carry one with us all the time.

Besides, since these days almost everyone has a smartphone, it turns out it would be an awesome idea to make an app for it. Because, as they say:

there’s an app for that

Where that is basically everything these days. If you find that there isn’t an app for some particular problem that you may have, that just may be your lucky break. Who knows, you just may end up having your 5 minutes of fame on the AppStore, until another clone of your app pushes you away.

Anyways, back to our calculator application; we don’t need any fancy options (at least not yet, in this 1.0 version), we’ll just stick with the basic mathematical operations like adding, subtracting, dividing and multiplying.

These basic operations will be our MVP (Minimum Viable Product), as the author Eric Ries explains in his awesome (and highly recommended) book Lean Startup. We can always add features later if it turns out that our idea was good. Or, we can pivot away from it, if it turns out it was not a next best thing after Flappy Bird. That way, we wouldn’t spend too much time and money building the app with a dozen features which, in the end, would not be used at all.

As for the user interface, you can use various tools that help with mocking up your application’s user interface (Balsamiq Mockups, Mockingbird, Mockup Builder). I tend to be old school about it, and I made a little hand drawing of how I imagined the app should look like, and this is what I came up with after few attempts:

Calculator interface prototype

Now that we know what our application needs to do and how it has to look like, let’s start by creating our interface.

We could create our interface by manually coding it in HTML/CSS, but we’re going to show a different approach here – the one which uses Ionic Creator, which is an awesome web application (soon to be a desktop app as well) that lets you drag&drop components that make up the user interface. As such, this is a great tool which helps in quick user interface prototyping.

The best thing is that you can then just download the created HTML/CSS (just recently they’ve added Ionic 3 support) and use it directly in your Ionic application. Of course, some additional changes will be needed later in the HTML and CSS code, but for creating a quick prototype, this will be more than enough.

Worth noting is that there are currently on the market lots of other tools for interface prototyping (InVision, Flinto, Figma 2.0). However, these tools don’t (at least not yet) have a “one-click download and ready for Ionic” option like Ionic Creator does.

Creating calculator interface with Ionic Creator

To use Ionic Creator you have to signup/login on their website. They are currently offering a 14-day trial (no credit card needed to sign up) of Creator Pro which is their best plan and has the following features:

On the initial screen, click the New Project button and fill out project’s name, type and Ionic version:

Please note that Ionic 3 code export is in Alpha mode currently – this will change in the coming months

The main screen of the Ionic Creator application looks like this:

In the upper left-hand side you’ll see the Pages panel, and inside it, you’ll see the Page item. Click on Page, and on the right-hand side change the Title to Calculator. Next, disable the Padding option by switching off the Padding checkbox under the Miscellaneous section on the right-hand side. The way this should look like now is shown on the image below:

First, we need some kind of a “display” which will show the numbers that we’re clicking. Ideally, we would use a <label> component, however, it’s not available in the Ionic Creator as of yet. So, for this, we will use the <input> element, and we can easily adjust this later when we download the generated HTML code.

Ionic Creator works in a drag&drop kind of way, which basically means that you can drag any component from the Components pane on the left-hand side and drop it on the Phone image in the center of the screen.

Since we concluded that we’d use the Input element, just drag&drop it to the Phone.

Select the Input component (by clicking on it in the Pages panel in the upper left corner mentioned before) and:

  • change Placeholder to 0 (zero digit)
  • change Name to display
  • remove the text under Title

The way this should look like now is shown on the image below:

Next, according to our mockup, we should add buttons that would represent the following:

  • digits from 0 to 9
  • adding (+)
  • substracting (–)
  • multiplying (x)
  • dividing (/)
  • modulo (%) – we are, after all, programmers, right? ?‍? ?

Also, we would need an equals button (=), a clear button (C) and a floating point (.) button.

In the first row we need to have three buttons, the ones representing the Clear operation (C), modulo operation (%) and divide operation (/). To accomplish this, we will use a Button component from the Components panel and drag&drop it just below the Input field on the screen. But, before you do that, you have to drag&drop the Container component as we will drop these operation buttons into it.

So, to sum up:
+ first, drag&drop the Container component, and then
+ drag&drop the Button component to the phone image inside the Container component

When done, change the Button’s Width property under the Style section on the right-hand side to Inline and color to Energized. Now, either repeat the process two more times or click on the duplicate icon which appears on the Button component once selected (just left of the x icon). Then change the Text of the buttons to C, % and / respectively. You should see something like this now in your Ionic Creator window:

Don’t worry that this now doesn’t look like in our design; we will deal with this at a later stage.

Those of you familiar with Ionic 1 (also covered in my previous book) know that we had the useful Button Bar component which doesn’t exist in Creator now, but we still have few options.

Now, repeat the process for the second row by first adding another Container component below the previous one and then adding four buttons: 7, 8, 9 and x into it. The additional change on the number buttons is that you need to set their color to Positive (TBH, ‘Positive` is the default color, so you basically won’t have to change anything).

Now you need to repeat the process by adding next three rows. The best thing you can do to speed up the process is to duplicate the whole row by clicking the duplicate icon:

and then change the button text to represent all the missing buttons per rows:

  • buttons representing 4, 5, 6 and a button representing subtraction (–)
  • buttons representing 1, 2, 3 and a button representing addition (+)

Number buttons should have a Positive style, and operation buttons should have an Energized style.

In the last row you should add three buttons (just delete one after you duplicate the whole row of four buttons):

  • one button representing 0, with the Positive style
  • one button representing floating point (.)
  • one button representing the Equals operation (=), with the Assertive style

Your interface should now look like this:

Don’t worry about the slight misalignment or padding; we’ll take care of this in the next chapter when we’ll be polishing our application and preparing it for the App/Play store.

So, this is it, we have our interface ready, and now we can export it by clicking on the Export icon in the header, as shown in the image below:

After this a popup, with the following content, appears:

Click the Download project ZIP button and save it to your computer.

Starting a project with Ionic CLI by using the template made in Ionic Creator

First, unzip the file that you’ve downloaded in the previous step. Then, start a new Ionic app by executing the following command in your Terminal:

ionic start Ionic3_2ndTutorial blank

Now go into the newly created Ionic3_2ndTutorial directory, and overwrite the src folder with the contents from your zip export. You will want to overwrite the app directory, pages directory, and index.html file.

Note: you’re free to name your project any way you want, I chose Ionic3_2ndTutorial in this example, and I used the ‘blank’ template.

Now, let’s see this in action; execute ionic lab and you should get an output like this:

[INFO] Starting app-scripts server: --lab --l --port 8100 --p 8100 --livereload-port 35729 --r 35729 --address 0.0.0.0 -
       Ctrl+C to cancel
[09:39:31]  watch started ... 
[09:39:31]  build dev started ... 
[09:39:31]  clean started ... 
[09:39:31]  clean finished in less than 1 ms 
[09:39:31]  copy started ... 
[09:39:31]  transpile started ... 
[09:39:33]  transpile finished in 1.83 s 
[09:39:33]  preprocess started ... 
[09:39:33]  deeplinks started ... 
[09:39:33]  deeplinks finished in 6 ms 
[09:39:33]  preprocess finished in 7 ms 
[09:39:33]  webpack started ... 
[09:39:33]  copy finished in 1.98 s 
[09:39:38]  webpack finished in 5.41 s 
[09:39:38]  sass started ... 
[09:39:39]  sass finished in 1.02 s 
[09:39:39]  postprocess started ... 
[09:39:39]  postprocess finished in 9 ms 
[09:39:39]  lint started ... 
[09:39:39]  build dev finished in 8.32 s 
[09:39:39]  watch ready in 8.36 s 
[09:39:39]  dev server running: http://localhost:8100/ 

[INFO] Development server running
       Local: http://localhost:8100

[09:39:42]  lint finished in 2.32 s

In the first tutorial we used the ionic serve command which starts up a local web browser and shows how our application would look like. This one is similar but in a way better as it can nicely show us how our app would look like on different platforms:

You can still use the ionic serve command if you like. The live preview is great for rapid development since you get to see changes instantly without needing to reload your browser manually.

If you get an error similar to this:
Error: tsconfig: Cannot read file '/DEV/Ionic3_2ndTutorial/src/tsconfig.json': ENOENT: no such file or directory, open '/DEV/Ionic3_2ndTutorial/src/tsconfig.json'.
then you didn’t run the ionic lab command in the project directory and so you should first cd into that directory (as mentioned in the previous step) and then run the ionic lab command.

Now, let’s go and see what our generated folder structure looks like and what is each folder responsible for.

Ionic application folder structure

If you open up the project in your editor (I’m using Visual Studio Code), you will see something like:

Now we’re going to explain what each of these files and folders represents in Ionic framework 3.

hooks folder

hooks folder contains code for Cordova hooks, which are used to execute some code during the Cordova build process. For example, Ionic uses Cordova’s after_prepare hook to inject platform specific (iOS, Android, Windows Phone) CSS and HTML code.

node_modules folder

node_modules folder contains all the Node modules that Ionic CLI uses in the background like for example babel, browserify, lodash, uglify, webpack to name just a few. There are 550+ tools in that folder ?, and you shouldn’t worry about it at this point at all.

resources folder

resources folder contains two files (icon.png and splash.png) and two folders (android and ios) which contain all the needed icon and splash screen sizes. Ionic has a simple command which creates all the icon and splash screen sizes for you automatically. We will cover that in more detail in the next tutorial.

src folder

src folder is the most important since it contains all the files our application is made of, and we will be spending most of our development time in this folder. This folder contains few files and additional sub folders which we’ll address in more detail in the next section titled Refactoring our application.

www folder

www folder contains the optimized version of our application (minimized, compressed, etc.). In future tutorials, we’ll show how easy it is to just take the contents of this folder and put it on your web server, and you would have the application ready and running. If you take a look at the live example of this project, this is exactly what I did.

.editorconfig file

.editorconfig is a configuration file for Visual Studio Code.

config.xml file

config.xml is a configuration file for the Cordova project (as you may remember from the first tutorial, Ionic is built on top of Cordova). It contains some meta information about the app like permissions and a list of Cordova plugins which are used in the app. To learn more about available settings in the config.xml file, please refer to the official documentation.

ionic.config.json file

ionic.config.json is a configuration file for Ionic, used to store meta information about an Ionic project and the associated Ionic.io cloud account. We’re not going to use Ionic.io cloud account just yet, we’ll show how to use it in the next chapter.

The contents of my ionic.config.json file is as follows:

{
  "name": "Ionic3_2ndTutorial",
  "app_id": "",
  "type": "ionic-angular"
}

It defines the name of the app and its type, along with the app_id in case you’ve created the Cloud account for this project (if you’ve answered Yes to the question when starting the project).

package.json file

package.json is a file used by npm to store versions of the npm packages installed in the current project.

npm (Node.js Package Manager) is a CLI tool which comes with Node.js installation and it’s used for installing other tools like aforementioned Browserify, Babel, etc…

Contents of my package.json file, shown below, is useful as we can see which Cordova plugins and dependencies we have installed on the project, as well as some meta information like name, version and description:

{
  "name": "Ionic3_2ndTutorial",
  "version": "0.0.1",
  "author": "Ionic Framework",
  "homepage": "http://ionicframework.com/",
  "private": true,
  "scripts": {
    "clean": "ionic-app-scripts clean",
    "build": "ionic-app-scripts build",
    "lint": "ionic-app-scripts lint",
    "ionic:build": "ionic-app-scripts build",
    "ionic:serve": "ionic-app-scripts serve"
  },
  "dependencies": {
    "@angular/common": "4.1.3",
    "@angular/compiler": "4.1.3",
    "@angular/compiler-cli": "4.1.3",
    "@angular/core": "4.1.3",
    "@angular/forms": "4.1.3",
    "@angular/http": "4.1.3",
    "@angular/platform-browser": "4.1.3",
    "@angular/platform-browser-dynamic": "4.1.3",
    "@ionic-native/core": "3.12.1",
    "@ionic-native/splash-screen": "3.12.1",
    "@ionic-native/status-bar": "3.12.1",
    "@ionic/storage": "2.0.1",
    "ionic-angular": "3.5.3",
    "ionicons": "3.0.0",
    "rxjs": "5.4.0",
    "sw-toolbox": "3.6.0",
    "zone.js": "0.8.12"
  },
  "devDependencies": {
    "@ionic/app-scripts": "2.0.2",
    "@ionic/cli-plugin-ionic-angular": "1.3.2",
    "typescript": "2.3.4"
  },
  "description": "An Ionic project"
}

package-lock.json file

package-lock.json file is automatically generated for any operation where npm modifies either the node_modules folder or package.json file. It describes the exact folder contents that was generated so that future installs can generate identical folder contents, regardless of intermediate dependency updates. This file is intended to be committed into source repositories so that your teammates (or continuous integration systems, if you have those set up) are guaranteed to install exactly the same dependencies.

.gitignore and README.md file

Both .gitignore and README.md are files related to GitHub.

I’m sure most of the readers know and use GitHub (and consequently Git), but just for brevity, let see how Wikipedia defines GitHub:

GitHub is a Web-based Git repository hosting service, which offers all of the distributed revision control and source code management (SCM) functionality of Git as well as adding its own features. Unlike Git, which is strictly a command-line tool, GitHub provides a Web-based graphical interface and desktop as well as mobile integration. It also provides access control and several collaboration features such as bug tracking, feature requests, task management, and wikis for every project.

So, Git on the other hand is (quoted from the official site):

a free and open source distributed version control system designed to handle everything from small to very large projects with speed and efficiency. Git is easy to learn and has a tiny footprint with lightning fast performance. It outclasses SCM tools like Subversion, CVS, Perforce, and ClearCase with features like cheap local branching, convenient staging areas, and multiple workflows.

If you’re not using Git (and Github) in your workflow, I highly encourage you to do so, as it will prove really useful in the long run.

Now that we got the basics out of the way let’s take a look at what the files above represent.

.gitignore is a configuration file for GitHub. Contents of the .gitignore file, shown below, basically instructs Git which folders it shouldn’t track and upload to GitHub.

# Specifies intentionally untracked files to ignore when using Git
# http://git-scm.com/docs/gitignore

*~
*.sw[mnpcod]
*.log
*.tmp
*.tmp.*
log.txt
*.sublime-project
*.sublime-workspace
.vscode/
npm-debug.log*

.idea/
.sass-cache/
.tmp/
.versions/
coverage/
dist/
node_modules/
tmp/
temp/
hooks/
platforms/
plugins/
plugins/android.json
plugins/ios.json
www/
$RECYCLE.BIN/

.DS_Store
Thumbs.db
UserInterfaceState.xcuserstate

README.md is a Markdown file used on GitHub to document the purpose and usage of your project. In general, IMHO, every project should have a decently written README.md file which explains the basic usage of the project along with instructions on how to run it, contribute to it, etc.

tsconfig.json file

tsconfig.json is TypeScript configuration file. We won’t go into the details here, but I encourage you to take a look at the official documentation.

{
  "compilerOptions": {
    "allowSyntheticDefaultImports": true,
    "declaration": false,
    "emitDecoratorMetadata": true,
    "experimentalDecorators": true,
    "lib": [
      "dom",
      "es2015"
    ],
    "module": "es2015",
    "moduleResolution": "node",
    "sourceMap": true,
    "target": "es5"
  },
  "include": [
    "src/**/*.ts"
  ],
  "exclude": [
    "node_modules"
  ],
  "compileOnSave": false,
  "atom": {
    "rewriteTsconfig": false
  }
}

tslint.json file

tslint.json is TypeScript Linter configuration file. Linter is a program which checks TypeScript code for readability, maintainability, and functionality errors. For more info, and to learn what the contents of the file shown below represents, please check the official docs.

{
  "rules": {
    "no-duplicate-variable": true,
    "no-unused-variable": [
      true
    ]
  },
  "rulesDirectory": [
    "node_modules/tslint-eslint-rules/dist/rules"
  ]
}

Refactoring our application

As said, we’ll be spending most of our development time in the src folder, and that’s why we mentioned it just briefly in the previous section. We’ll take a full deep dive into it here, by explaining each file (that we’ll change) in detail.

Finally, we’ll add the calculator logic so that our calculator will work as expected.

Generally, putting all the code in one file and mixing logic and presentation (JavaScript and HTML code) is simply a big NO-NO, and often referred to as spaghetti code. You can learn more about refactoring your code from the cult book Refactoring: Improving the Design of Existing Code by Martin Fowler, Kent Beck, and others. If you’re searching for a bit lighter introduction to refactoring and good programing practices, in general, I can’t recommend the classic Code Complete 2 by Steve McConnell enough. I’ve read the book way back in 2011, and you can read my notes from the first part of the book here.

^ This was the comment from the first edition of this book (covering Ionic 1). I am happy to report that ever since Ionic has done an awesome job in separating the logic and presentation into components. Mainly this benefit comes from Angular (currently at version 4.x).

index.html file

The starting point of our Ionic application is index.html, whose contents is as follows:

<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
  <meta charset="UTF-8">
  <title>Ionic3Calculator</title>
  <meta name="viewport" content="width=device-width, initial-scale=1.0, minimum-scale=1.0, maximum-scale=1.0, user-scalable=no">
  <meta name="format-detection" content="telephone=no">
  <meta name="msapplication-tap-highlight" content="no">

  <link rel="icon" type="image/x-icon" href="assets/icon/favicon.ico">
  <link rel="manifest" href="manifest.json">
  <meta name="theme-color" content="#4e8ef7">

  <!-- cordova.js required for cordova apps -->
  <script src="cordova.js"></script>

  <!-- un-comment this code to enable service worker
  <script>
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('service-worker.js')
        .then(() => console.log('service worker installed'))
        .catch(err => console.log('Error', err));
    }
  </script>-->

  <link href="build/main.css" rel="stylesheet">

</head>
<body>

  <!-- Ionic's root component and where the app will load -->
  <ion-app></ion-app>

  <!-- The polyfills js is generated during the build process -->
  <script src="build/polyfills.js"></script>

  <!-- The vendor js is generated during the build process
       It contains all of the dependencies in node_modules -->
  <script src="build/vendor.js"></script>

  <!-- The bundle js is generated during the build process -->
  <script src="build/main.js"></script>

</body>
</html>

I’m expecting that you have a decent understanding of HTML, so I won’t explain every HTML tag.

In the index.html file we’re loading in the CSS and JS files from the build folder. The most important tag is <ion-app></ion-app> since this is where we’ll be loading our application.

app folder

The app folder with the src folder is the starting point of every Ionic3 application.

app.components.ts file

Here I won’t go into too much detail (as this post is long enough on its own now ?) but I want to show you where your page is being loaded in. The contents of the file should be as follows:

import { Component } from '@angular/core';
import { Platform } from 'ionic-angular';
import { StatusBar } from '@ionic-native/status-bar';
import { SplashScreen } from '@ionic-native/splash-screen';

import { CalculatorPage } from '../pages/calculator/calculator';

@Component({
    templateUrl: 'app.html'
})

export class MyApp {
    rootPage: any = CalculatorPage;

    constructor(platform: Platform, statusBar: StatusBar, splashScreen: SplashScreen) {
        platform.ready().then(() => {
            // Okay, so the platform is ready and our plugins are available.
            // Here you can do any higher level native things you might need.
            statusBar.styleDefault();
            splashScreen.hide();
        });
    }
}

The important line here is rootPage: any = CalculatorPage; which sets the root page of your app to the CalculatorPage, which again is imported at the beginning of the file:

import { CalculatorPage } from '../pages/calculator/calculator';.

platform.ready event is triggered after the device (your mobile phone on which the application is started) is all set up and ready to use. This includes plugins which are used in this project. If you would try to check if some plugin is available outside of the ready function callback, you could get wrong results because it is possible that some plugin would not have been set up just yet. You can learn more about Ionic Platform utility methods here.

Important to note are the places in code where and how the same CalculatorPage is injected in the app.module.ts file and added in the @NgModule declarations and entryComponents.

In this app folder, in the file app.scss you could put some style rules that you want to apply globally for your application. We’ll cover styling in the next tutorial where we’ll polish our existing calculator application.

cordova.js, manifest.json and service-worker.json files

We won’t be dealing with these three files in this tutorial. We’ll leave them for another tutorial in which we’ll explain how to create a PWA (Progressive Web App) with Ionic and how to use native plugins (accessing Camera, etc.).

Calculator logic with controllers

Ionic Creator has nicely generated a calculator page for us in the pages folder:

As mentioned before, the organization like this is so much better from what we had before as now we have three files per each component:

  • HTML template file (calculator.html)
  • SASS file (calculator.scss)
  • TypeScript file (calculator.ts)

This way we have the presentation (HTML + CSS) and logic (TS) separated and this is something you should always strive for.

Ionic Creator generated the following code for our calculator.ts file:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
    selector: 'page-calculator',
    templateUrl: 'calculator.html'
})
export class CalculatorPage {
    constructor(public navCtrl: NavController) {

    }
}

This is a bare bones code template where we’re importing the Component and NavController components; then we’re defining our Component decorator selector and templateUrl. Finally, we’re exporting the CalculatorPage class and defining the constructor inside it.

The templateUrl defines the location of the HTML template, and the selector defines the HTML tag (<page-calculator></page-calculator>) that will be used in our template once the app is generated:

Here we’re going to add the small piece of code which will make our app justWork™. Just add this code in the CalculatorPage class:

result = '';

btnClicked(btn) {
    if (btn == 'C') {
        this.result = '';
    }
    else if (btn == '=') {
        this.result = eval(this.result);
    }
    else {
        this.result += btn;
    }
}

In this code, we’re defining a variable result, so that we can show it in our template file (calculator.html).

Next, we defined a new function called btnClicked which accepts one parameter named btn. Inside the function, we’re checking for the passed parameter, and we have three cases based on the value of the parameter that is passed:

  • if the parameter equals C then we’re clearing the result
  • if the parameter equals = then we’re calculating the equation and showing the result
  • in any other case we’re just appending the button’s value to the current equation

Please note that because of brevity we haven’t added any additional checks like if someone accidentally (or intentionally) clicks two times on a button which represents some operation. We will “fix” this in the next chapter when we’ll be polishing the application. Also, you may have read on the Internet that using eval is wrong or just bad. True, it can be bad if used to evaluate some other user input, but in this case, we’ll be fine.

Finishing the calculator template

The only thing which is left for us to do is to add the appropriate function calls on the buttons in the calculator.html template. All that we have to do is add the (click)="btnClicked() function call to each button, and pass in the appropriate parameter. The template that Ionic Creator created for us looks like this:

<ion-header>
    <ion-navbar>
        <ion-title>
            Calculator
        </ion-title>
    </ion-navbar>
</ion-header>

<ion-content id="page1">
    <form id="calculator-form1">
        <ion-item id="calculator-input1">
            <ion-label></ion-label>
            <ion-input type="text" placeholder="0" name="display"></ion-input>
        </ion-item>
    </form>

    <div id="calculator-container3">
        <button id="calculator-button1" ion-button color="energized"> C </button>
        <button id="calculator-button2" ion-button color="energized"> % </button>
        <button id="calculator-button3" ion-button color="energized"> / </button>
    </div>

    <div id="calculator-container6">
        <button id="calculator-button10" ion-button color="positive"> 7 </button>
        <button id="calculator-button11" ion-button color="positive"> 8 </button>
        <button id="calculator-button12" ion-button color="positive"> 9 </button>
        <button id="calculator-button13" ion-button color="energized"> x </button>
    </div>

    <div id="calculator-container7">
        <button id="calculator-button14" ion-button color="positive"> 4 </button>
        <button id="calculator-button15" ion-button color="positive"> 5 </button>
        <button id="calculator-button16" ion-button color="positive"> 6 </button>
        <button id="calculator-button17" ion-button color="energized"> - </button>
    </div>

    <div id="calculator-container8">
        <button id="calculator-button18" ion-button color="positive"> 1 </button>
        <button id="calculator-button19" ion-button color="positive"> 2 </button>
        <button id="calculator-button20" ion-button color="positive"> 3 </button>
        <button id="calculator-button21" ion-button color="energized"> + </button>
    </div>

    <div id="calculator-container9">
        <button id="calculator-button22" ion-button color="positive"> 0 </button>
        <button id="calculator-button23" ion-button color="positive"> , </button>
        <button id="calculator-button25" ion-button color="energized"> = </button>
    </div>
</ion-content>

I have to note that in the current version of Ionic Creator export they still have the old names for colors and we will have to change this. The old Ionic 1 style colors were this:

$light:                           #fff !default;
$stable:                          #f8f8f8 !default;
$positive:                        #387ef5 !default;
$calm:                            #11c1f3 !default;
$balanced:                        #33cd5f !default;
$energized:                       #ffc900 !default;
$assertive:                       #ef473a !default;
$royal:                           #886aea !default;
$dark:                            #444 !default;

The new color names are now these (defined in the src/theme/variables.scss file):

$colors: (
    primary:    #488aff,
    secondary:  #32db64,
    danger:     #f53d3d,
    light:      #f4f4f4,
    dark:       #222,
    energized: #ffc900;
);

In our template, where we have color="positive" we can just delete that as that is now the default color if no color is defined on the button.

So, we won’t change the existing names, as then we would break the code for where this particular variable name is used. We will just add our own class for energized so that the new colors array will look like this:

$colors: (
    primary:    #488aff,
    secondary:  #32db64,
    danger:     #f53d3d,
    light:      #f4f4f4,
    dark:       #222,
    energized: #ffc900
);

Additionally, somewhat a departure from the design, we will add the danger color to the buttons C and =.

This is how the template should look like now:

<ion-header>
    <ion-navbar>
        <ion-title>
            Calculator
        </ion-title>
    </ion-navbar>
</ion-header>

<ion-content id="page1">
    <form id="calculator-form1">
        <ion-item id="calculator-input1">
            <ion-label></ion-label>
            <ion-input type="text" placeholder="0" name="display" [(ngModel)]="result"></ion-input>
        </ion-item>
    </form>

    <div id="calculator-container3">
        <button id="calculator-button1" ion-button color="danger" (click)="btnClicked('C')"> C </button>
        <button id="calculator-button2" ion-button color="energized" (click)="btnClicked('%')"> % </button>
        <button id="calculator-button3" ion-button color="energized" (click)="btnClicked('/')"> / </button>
    </div>

    <div id="calculator-container6">
        <button id="calculator-button10" ion-button (click)="btnClicked('7')"> 7 </button>
        <button id="calculator-button11" ion-button (click)="btnClicked('8')"> 8 </button>
        <button id="calculator-button12" ion-button (click)="btnClicked('9')"> 9 </button>
        <button id="calculator-button13" ion-button color="energized" (click)="btnClicked('*')"> * </button>
    </div>

    <div id="calculator-container7">
        <button id="calculator-button14" ion-button (click)="btnClicked('4')"> 4 </button>
        <button id="calculator-button15" ion-button (click)="btnClicked('5')"> 5 </button>
        <button id="calculator-button16" ion-button (click)="btnClicked('6')"> 6 </button>
        <button id="calculator-button17" ion-button color="energized" (click)="btnClicked('-')"> - </button>
    </div>

    <div id="calculator-container8">
        <button id="calculator-button18" ion-button (click)="btnClicked('1')"> 1 </button>
        <button id="calculator-button19" ion-button (click)="btnClicked('2')"> 2 </button>
        <button id="calculator-button20" ion-button (click)="btnClicked('3')"> 3 </button>
        <button id="calculator-button21" ion-button color="energized" (click)="btnClicked('+')"> + </button>
    </div>

    <div id="calculator-container9">
        <button id="calculator-button22" ion-button (click)="btnClicked('0')"> 0 </button>
        <button id="calculator-button23" ion-button (click)="btnClicked('.')"> . </button>
        <button id="calculator-button25" ion-button color="danger" (click)="btnClicked('=')"> = </button>
    </div>
</ion-content>

As you can see from the code, we’re passing to the function an argument which represents the clicked button.

Also, worth noting is that we used the

[(ngModel)]="result"

on the input element, so that we can access it from the controller through the Angular two-way binding and that we can enter some formula in the input field ourselves as well.

We could have used just the one-way binding like this:

[ngModel]="result"

but if we manually entered something in the input field, it would not ‘propagate’ to our code.

Run the application

Now you can run the application by executing the command

ionic lab

and you should see your awesome calculator open up in your browser:

as noted before, don’t worry this doesn’t look ‘slick’ or that it doesn’t ‘pop’ (or some other nonsense word the ‘knowledgeable’ people use these days), we’ll take care of this in the following tutorial.

The best thing, it should ? also work as expected. So, if you try to enter something like 2+3-10*2 and tap on = you should get the expected -15 (yes, operator precedence is taking place correctly).

We also have the floating point arithmetic like 2.3+3.2 equals 5.5.

As mentioned at the beginning of this chapter, you can take a look at the source code on GitHub, or you can take a look at the live example of this application.

Conclusion

In this chapter, we covered how to create a calculator application step by step. We showed how to create a mockup of our idea; then we showed how to create an interface by using Ionic Creator, and finally how to implement calculator’s logic.

In the next chapter, we’re going to take a look at how to test our application on the real physical devices, and how to use Ionic View App to share our application with other users without going through the app store. Also, we’re going to take a look at how to implement Google Analytics and Google Admob ads, and how to prepare our application for the stores. Additionally, we’ll take a look at how to customize the icons and the application’s splash screen.

Until next time, keep on improving ?

How to create a #calculator application with @Ionicframework 3 by using #Ionic Creator for UI https://t.co/ElzEhU8Jrc

— Nikola Brežnjak (@HitmanHR) August 2, 2017

Ionic3

How to get started with Ionic framework 3 on Mac and Windows

This is the first post in a series of posts which will teach you how to take advantage of your web development knowledge in building hybrid applications for iOS and Android with Ionic framework 3 (I’ll use Ionic in the rest of the post).

This is an update of the series of posts that I did for the original version of the Ionic framework, and you can read it here.

This first post explains:

  • How to make an app these days
  • What actually is Ionic framework
  • How is Ionic 3 different from Ionic 1 and 2
  • How to install Ionic on both Mac and Windows
  • How to use Ionic CLI to start an Ionic project
  • How to run an Ionic application

You can read the second post in the series here: How to create a calculator application with Ionic framework 3 by using Ionic Creator for UI.

Why should you listen to me?

This is in no way my attempt at feeding my ego, it’s just to give you soundness of mind that what I’m writing here may actually be useful to you.

  • Wrote a book about the original Ionic framework, and you can get it for free
  • Wrote for Pluralsight on the topic of Ionic: Ionic Framework: A definitive 10,000-word guide
  • In the top #3 all time answerers for the ionic tag on StackOverflow. If you want to see what those answers actually are, you can take a look at my StackOverflow profile.
  • Was a technical reviewer for the book Getting started with Ionic

Introduction

…up to 90% of mobile time is spent in apps

You’re bombarded with reports like this and this that users tend to spend way more time on their phones and especially in apps (rather than surfing the web using their phones) and you decided that it’s time to learn how to make an app.

If you’re a web developer, you have a decent knowledge of HTML, CSS, and JavaScript; also, you’re most likely using one of the ever so slightly popular frameworks these days like Angular, React or Ember, to name a few. If you’re even proficient enough with the MEAN stack, you are a well-rounded full stack developer, and you basically have it all. Well, except the apps part, right?

If you want to see what’s all that fuss about the MEAN stack, you can check out the free four-part tutorial series that I wrote for HackHands, starting with the first post on How to get started on the MEAN stack.

But, where to start with making an app? Could you use some of your existing skills? Up until fairly recently, if you wanted to make an app for (currently) two most popular mobile operating systems (iOS and Android – sorry Windows Phone ?) your only bet was to make the so-called, native application by using the SDKs of the intended platforms.

This, of course, meant that you needed to make two versions of your application; one for iOS and one for Android. If you are a solo developer, chances that you’re proficient in both are not so great. Even if you are; I bet you’re favoring one platform over the other, right?

Therefore, for some time, developers were opting for either iOS or Android, whereas big firms had two developing departments, one for each platform.

Nowadays, luckily, with the help of Ionic Framework, and few others like React Native, NativeScript, Fuse, you can create an application by using the skills you, as a web developer, already have. If you’re not a web developer, don’t fret – this isn’t rocket science or machine learning… ?

How can you make an app these days?

We’ve kind of touched all three in the Introduction section, but let’s keep it nice and concise and list them here as well. So, there are actually few ways that you can make an application for mobile devices these days:

  • Native app
  • Mobile website (PWA)
  • Hybrid app
  • Xamarin, ReactNative, NativeScript!?

Now, let’s talk a bit more about the pros and cons of each of them.

Native app

As mentioned previously, you can make an app specifically for iOS and Android by using their specific SDKs. If you want to build a native application for iOS you have to:

  • have a Mac computer. Sure, there are ways around it, but I honestly don’t recommend them; for starters, a cheap Mac Mini will do just fine
  • download Xcode from the App Store (it’s actually free)
  • buy the Apple Developer license that costs 99$ per year. Even if you don’t make any new apps after publishing your one app to the App Store, you’ll still have to renew your subscription every year to keep your app in the App Store ??

You can write the apps by using the Swift language, or it’s predecessor ObjectiveC.

If we’re honest here, I think that Swift is a great step up from the clunky ObjectiveC, but that’s just my own opinion (some people, of course, disagree). Anyways, if you ever decide to go native just make sure you go with Swift as you’ll get to know your way around it way sooner than with ObjectiveC, especially if you have a background in web development.

If you want to build a native application for Android you have to:

  • have any computer
  • download the appropriate SDKs (we’ll cover this in the next section)
  • buy the Google Developer license which is a one time 25$ purchase

One of the pros of a native applications would be it’s speed and direct access to a native API (you don’t have to use any middleman wrappers, like in hybrid apps). A definite con of a native applications is that you need to build two (or more) applications, one for each desired platform.

Mobile website (PWA)

A mobile website is actually a “normal” website (yeah, don’t go jumping because of the terminology; you’re smart, you get the point) that you visit with your browser on your phone, designed specifically to adapt to your phone’s screen. As we’ve noted in the Introduction section, researches show that in today’s world mobile websites tend to have a way lower engagement than they used to.

Developers used to make specific sites just for mobile browsers (on it’s own domain; usually m.domain.com) but this proved to be hard to maintain. A practice called responsive website design is used these days, where you basically have one HTML codebase, and you determine the look for specific devices (based on resolutions) by using the so-called media queries.

A great example of a mobile framework is jQuery mobile that is soon coming out with its new 1.5 version (here’s their alpha changelog), so we’ll see if they bring something new to the table. From my personal experience with the framework from four years ago, I have all but good words for it; so, definitely use it if you’re “only” making a mobile version of your web application.

A definite advantage of the mobile websites is that you can update them as you see fit, without waiting for the approval from Apple or Google. One of the disadvantages is definitely the fact that the mobile websites these days have way lower engagement than they used to, and that you can’t basically use any of the additional phone features like for example camera or GPS.

Since this is an update of the post, few things have changed and if you only want to make a ‘mobile website’. I’d suggest looking into PWA (Progressive Web Apps) as they are the new cool nowadays, and some go even as far as saying that native apps are doomed due to PWAs, but we won’t be focusing on that here.

Good news for those of you who also want to create PWAs of your apps – with Ionic you can! Ionic enables you to get the best of both worlds: cross-platform app store deployment on iOS, Android, and Windows, along with deployment to the mobile web as a Progressive Web App with the same code. But, let’s not be hasty, we’ll cover that in the next section.

Hybrid app

A hybrid app is a basically a mobile application, written with the same set of languages that you use when building websites, with the addition that it contains an isolated browser instance, called WebView, which runs this web application inside of a native app. Hybrid apps can access the mobile device and use the additional phone features like for example camera or GPS.

A definite advantage of the hybrid apps is the fact that you can access the additional phone features via plugins and that you can do all the development with the same set of skills as you use when developing “normal” web applications.

One of the disadvantages is the fact that, even though it’s improving, the so-called Web View has its limitations in terms of speed. Also, it might not be best suited to choose hybrid if you’re using a lot of additional phone features, as you would have to use a lot of plugins which would slow the app down. But, from my personal experience, we have 30+ plugins (yeah, don’t ask) that we use in our app and we’re getting away with it ?.

Finally, you would definitely not use it if you’re on a quest to make the next best game with full-blown 3D graphics.

Xamarin, ReactNative, NativeScript!?

We have to be fair here and mention the new players who promise the fact of having a full API access without any additional plugins and produce ‘actual’ native apps with very high percentage of shared code. So, the app is not run in the Web View like in Ionic’s case which is a boost to the app speed.

If you’re coming from .NET background and you want to create an app; then you can stop reading here, as from what I’ve seen Xamarin is a sure bet for you and you’ll instantly feel at home.

If you’re a React guy, then ReactNative may just be up your alley. As they say on their website:

With React Native, you don’t build a “mobile web app”, an “HTML5 app”, or a “hybrid app”. You build a real mobile app that’s indistinguishable from an app built using Objective-C or Java. React Native uses the same fundamental UI building blocks as regular iOS and Android apps. You just put those building blocks together using JavaScript and React.

As for NativeScript; to be honest, I don’t have experience with it, but it seems they’re in a similar boat as ReactNative as they also give you the NativeUI without web views.

You can check out a good blog post on the topic of Ionic vs. NativeScript vs. ReactNative here.

What is Ionic and why it’s so good

As I gave an answer on StackOverflow:

Disclaimer: This will sound like an advertisement, so I have to say I’m in no way affiliated with Ionic, I just happen to like it so much that I’m sharing the love for it.

Ionic is so much more than “just” a UI framework. Ionic allows you to:

  • have truly only one single codebase and deploy to iOS, Android, and Windows, along with the mobile web as a Progressive Web App
  • generate icons and splash screens for all devices and device sizes with a single command: ionic cordova resources. This alone saves you at least a day of image preparing for various sizes.
  • instantly update your apps with code changes, even when running directly on your device with ionic cordova run --livereload
  • build and test iOS and Android versions side-by-side and see changes instantly with ionic lab
  • share your Ionic apps with clients, customers, and testers all around the world without ever going through the App Store with ionic upload
  • easily access the full native functionality of the device using Ionic Native
  • Also, Drifty (the team behind the Ionic framework) is building a full-stack backend services and tools for your Ionic app like Live updating (for deploying a new version without going through Apple review process! – this is huge!), Push notifications, Cloud packaging, Ionic Creator etc.
  • Ionic CLI (command line interface) uses Cordova in the backend and allows you to build (directly using Ionic CLI) apps for iOS and Android (just by doing ionic cordova build ios or ionic cordova build android).
  • Ionic uses Angular as a frontend framework so if you’re familiar with it, it will come as a bonus. Yes, the newest version of Ionic (currently 3) uses the newest and coolest Angular (currently 4) (which was a total rewrite from the Angular 1 version)
  • All in all, I personally think Ionic framework has a bright future, so if nothing else – give it a try I bet you’ll like the ease of making an app with it.

Do I have your attention now? Great, let’s install all the needed prerequisites in the next section and start using Ionic!

How is Ionic 3 different from Ionic 1 and 2

Josh Morony wrote about 7 Reasons Why Ionic 2 Is Better Than Ionic 1 and made a video about What Ionic 3 means to Ionic 2, and I encourage you to check them out to learn more about:

  • why Ionic 2 is totally different (and better) from Ionic 1 and
  • why Ionic 3 is not that much different from Ionic 2

The biggest change comes down to the fact that Ionic 2 and 3 use the new Angular (now at version 4), whereas Ionic 1 uses the old Angular 1.

Now, don’t get me wrong – we all seem to love the ‘new shiny things’, but I can tell you from my experience that even with Ionic 1 you can still make great apps! So, even if you’re awesome at Angular 1 I’d suggest you go for Ionic 3, as the benefits are truly amazing. Plus, you don’t want to be working in a 5 years ‘old’ technology, now do you? ?

Installing prerequisites for both Mac and Windows

We need to have Node.js and Git installed in order to install both Ionic and Cordova. If you already have (and if you’re a web developer chances are that you do) these tools installed, you can skip this section, and go straight to installing Ionic.

Installing Node.js

In order to download Node.js, visit https://nodejs.org/en/download/, where you’ll see the following options:

Installation on Windows and Mac OS is simple as you just have to download and run the appropriate installer and follow the familiar instructions (next, next, next, sure I accept, next, finish ).

If you have brew on your Mac then you can also install Node.js with:

brew install node

In both cases, npm (Node Package Manager – used to install other packages) will be installed along with Node.js.

To verify that you installed Node.js correctly on a Windows machine, run the following command in your Command prompt (or, even better, use Console 2):

node -v

You should get an output similar to: v8.0.0.

To verify that you installed Node.js correctly on your Mac, run the same command as above in your Terminal (or, even better, use iTerm), and you should get the same similar output as above.

To verify that you have npm install, just run: npm -v and you should get an output similar to: 5.0.1

Installing Git

In order to install Git, visit http://git-scm.com/download, where you’ll see the following options:

Installation on Windows and Mac OS is as simple as for Node.js as you just have to download and run the appropriate installer and follow the, yet again, familiar instructions.

To verify that you installed Git correctly on your Windows/Mac machine, run the following command in your Command prompt/Terminal:

git

You should get an output similar to:

usage: git [--version] [--help] [-C ] [-c name=value]
[--exec-path[=]] [--html-path] [--man-path] [--info-path]
[-p | --paginate | --no-pager] [--no-replace-objects] [--bare]
[--git-dir=] [--work-tree=] [--namespace=]
<command></command> []

These are common Git commands used in various situations:

start a working area (see also: git help tutorial)
clone Clone a repository into a new directory
init Create an empty Git repository or reinitialize an existing one

work on the current change (see also: git help everyday)
add Add file contents to the index
mv Move or rename a file, a directory, or a symlink
reset Reset current HEAD to the specified state
rm Remove files from the working tree and from the index

examine the history and state (see also: git help revisions)
bisect Use binary search to find the commit that introduced a bug
grep Print lines matching a pattern
log Show commit logs
show Show various types of objects
status Show the working tree status

grow, mark and tweak your common history
branch List, create, or delete branches
checkout Switch branches or restore working tree files
commit Record changes to the repository
diff Show changes between commits, commit and working tree, etc
merge Join two or more development histories together
rebase Reapply commits on top of another base tip
tag Create, list, delete or verify a tag object signed with GPG

collaborate (see also: git help workflows)
fetch Download objects and refs from another repository
pull Fetch from and integrate with another repository or a local branch
push Update remote refs along with associated objects

'git help -a' and 'git help -g' list available subcommands and some
concept guides. See 'git help <command></command>' or 'git help '
<command></command> to read about a specific subcommand or concept.
<command></command> ```

You don't have to worry if you don't know how to use Git since you won't be needing it directly (npm uses it to download packages). However, if you would like to learn (and there's no reason why you shouldn't expand your knowledge), you can check out this [good interactive tutorial](https://try.github.io/levels/1/challenges/1) made by CodeSchool.

## Installing Ionic
If you've installed the needed prerequisites from the previous section, then in order to install Ionic (both on Mac and Windows) you just have to run the following command:

`npm install ionic cordova -g`

Ionic uses [Cordova](https://cordova.apache.org/) in the background for packaging up the native app, thus the need for it. We're using the **-g** flag here, in order to install the packages **ionic** and **cordova** [globally](https://docs.npmjs.com/getting-started/installing-npm-packages-globally).

To verify that you've installed Ionic correctly on your Windows/Mac machine, run the following command in your Command prompt/Terminal:

`ionic -v`

You should get an output similar to:

`3.4.0`

To verify that you've installed Cordova correctly on your Windows/Mac machine, run the following command in your Command prompt/Terminal:

`cordova -v`

You should get an output similar to:

`7.0.1`

If you had Node.js installed before (and haven't used it much since), you may get a notification like this:


Upgrade warning – for the CLI to run correctly,
it is highly suggested to upgrade the following:

Please update your Node runtime to version >=0.12.x



To resolve this issue, just update Node.js; either by re-downloading it (on Windows) or by executing the following command in the Terminal (on a Mac): `brew update; brew upgrade node` > I would like to take a moment here and encourage you to post a comment about any problems you may come across (and from my experience from StackOverflow there tends to be quite a lot of them ?) with these (seemingly simple) installation tasks. There always tends to be some older version of Node.js installed, or problems with cache and npm, blah blah blah... I will do my best to try to resolve your issue. ## Using Ionic CLI If you run `ionic` in your Terminal/Command prompt you will get an output similar to the one below:

CLI 3.4.0
Usage:

$ ionic [–help] [–verbose] [–quiet] [] [options]
$ ionic [–confirm] [–no-interactive] [–yarn] [–no-timeout]

Global Commands:

docs ………………… Open the Ionic documentation website
info ………………… Print system/environment info
login ……………….. Login with your Ionic ID
signup ………………. Create an Ionic account
start ……………….. Create a new project
telemetry ……………. Opt in and out of telemetry

Project Commands:

You are not in a project directory.


What you got is actually a nice summary of the global commands that you can run using the ionic CLI, along with their short descriptions. _Btw, if you're wondering what this CLI thing is (and you haven't [Googled it yet](https://en.wikipedia.org/wiki/Command-line_interface)); it's actually an acronym for Command Line Interface, and in Ionic terms it's actually a tool that makes it easier to [start, build, run, and emulate, (and a lot more), Ionic apps](http://ionicframework.com/docs/cli/)._ In the following chapters we will cover most of these commands, but for now, let's not burden you too much, and let's do a quick skin deep dive by making a simple project using `ionic start` command. ## Starting a project with Ionic CLI by using the existing templates Cool, you've made it so far - I promise, you're going to see some code now! ![](http://i.imgur.com/Y8FXaWm.jpg) Ionic CLI allows you to start and initialize your project by using the aforementioned `ionic start` command. If you take a look at [the official documentation for the start command](http://ionicframework.com/docs/cli/start/) you will see something like the following definition: `ionic start [&lt;name&gt;] [&lt;template&gt;]` >❗If you're familiar with Ionic 1, then you'll notice that they've changed it a bit. If you still want to run Ionic 1 apps with an Ionic CLI version 3 or above, you need to pass in the `--type` flag like this: `ionic start myApp --type ionic1` If you just run `ionic start appname` the Ionic CLI will make a bootstrap application with all the needed parts in the **appname** folder, with the so-called **blank** template. In case you want to see the list of all the starter projects, you can run `ionic start --list`:

ionic start –list
tabs …………… ionic-angular A starting project with a simple tabbed interface
blank ………….. ionic-angular A blank starter project
sidemenu ……….. ionic-angular A starting project with a side menu with navigation in the content area
super ………….. ionic-angular A starting project complete with pre-built pages, providers and best practices for Ionic development.
conference ……… ionic-angular A project that demonstrates a realworld application
tutorial ……….. ionic-angular A tutorial based project that goes along with the Ionic documentation
aws ……………. ionic-angular AWS Mobile Hub Starter
tabs …………… ionic1 A starting project for Ionic using a simple tabbed interface
blank ………….. ionic1 A blank starter project for Ionic
sidemenu ……….. ionic1 A starting project for Ionic using a side menu with navigation in the content area
maps …………… ionic1 An Ionic starter project using Google Maps and a side menu


Additionally, you can use Github repo starters and Codepen URL starters. In our example, we will use the **sidemenu** template, so execute the following command from your Terminal/Command prompt: `ionic start Ionic3_1stTutorial sidemenu` You should see something similar to the following output:

✔ Creating directory ./Ionic3_1stTutorial – done!
[INFO] Fetching app base (https://github.com/ionic-team/ionic2-app-base/archive/master.tar.gz)
✔ Downloading – done!
[INFO] Fetching starter template sidemenu (https://github.com/ionic-team/ionic2-starter-sidemenu/archive/master.tar.gz)
✔ Downloading – done!
✔ Updating package.json with app details – done!
✔ Creating configuration file ionic.config.json – done!
[INFO] Installing dependencies may take several minutes!

npm install
✔ Running command – done!
npm install –save-dev –save-exact @ionic/cli-plugin-ionic-angular@latest
✔ Running command – done!
git init
✔ Running command – done!
git add -A
✔ Running command – done!
git commit -m “Initial commit” –no-gpg-sign
✔ Running command – done!

♬ ♫ ♬ ♫ Your Ionic app is ready to go! ♬ ♫ ♬ ♫

Run your app in the browser (great for initial development):
ionic serve

Run on a device or simulator:
ionic cordova run ios

Test and share your app on a device with the Ionic View app:
http://view.ionic.io

? Link this app to your Ionic Dashboard to use tools like Ionic View? No

Go to your newly created project: cd ./Ionic3_1stTutorial


## Running the Ionic application Now that we've initialized our Ionic application based on the **sidemenu** template, we have to run it in order to see what Ionic CLI generated for us. First, change the directory to the name of the application you gave in the `ionic start` command. In our case, that's: `cd Ionic3_1stTutorial`. If you open up the project in your editor (I use [Visual Studio Code](https://code.visualstudio.com/) with Solarized Dark theme nowadays, after being loyal, and paying ?, customer of [Sublime Text 3](http://www.sublimetext.com/3)) you will see the following folder structure: ![](http://i.imgur.com/cecGiB3.png) In the following chapters, we will spend most of the time in the **app** folder. > ❗ Those of you coming from Ionic 1 background be wary of the `www` folder - don't touch it at all, as this is where all the transpiled/compressed code is saved. `src/app` is your new `www` folder. > Since Ionic 3 is based on [Angular](https://angular.io/) framework, you will need at least a basic understanding of it, and you can start exploring it with a [free interactive tutorial](https://www.codeschool.com/courses/accelerating-through-angular) by CodeSchool, or you can check out my post for Pluralsight: [Getting started with Angular 2 by building a Giphy search application](https://www.pluralsight.com/guides/front-end-javascript/getting-started-with-angular-2-by-building-a-giphy-search-application). Please note that this is very different from Angular 1 that you (and me ?) was accustomed to. There are few ways in which you can get your Ionic application running: + `ionic serve` - starts the app in a local web browser + `ionic cordova emulate android` - starts the app in an emulator (in this example Android is used; you can also use **ios** if you're on a Mac and have all the prerequisites installed) + `ionic cordova run android` - starts the app on the actual device that's plugged into your computer + `ionic cordova build android` - creates an **.apk** file which you can physically copy to your Android device and run it (this scenario doesn't work for iOS devices in normal circumstances; you have to go through Xcode, as we'll describe in detail in the next chapter) So, now run the following command in your Terminal/Command prompt: `ionic serve` You should see the following similar output:

[INFO] Starting app-scripts server: –port 8100 –p 8100 –livereload-port 35729 –r 35729 –address 0.0.0.0 – Ctrl+C to
cancel
[13:56:20] watch started …
[13:56:20] build dev started …
[13:56:20] clean started …
[13:56:20] clean finished in 1 ms
[13:56:20] copy started …
[13:56:20] transpile started …
[13:56:22] transpile finished in 2.03 s
[13:56:22] preprocess started …
[13:56:22] deeplinks started …
[13:56:22] deeplinks finished in 11 ms
[13:56:22] preprocess finished in 13 ms
[13:56:22] webpack started …
[13:56:22] copy finished in 2.20 s
[13:56:29] webpack finished in 6.91 s
[13:56:29] sass started …
[13:56:30] sass finished in 953 ms
[13:56:30] postprocess started …
[13:56:30] postprocess finished in 10 ms
[13:56:30] lint started …
[13:56:30] build dev finished in 9.95 s
[13:56:30] watch ready in 10.03 s
[13:56:30] dev server running: http://localhost:8103/

[INFO] Development server running
Local: http://localhost:8103

[13:56:35] lint finished in 5.13 s
“`

Also, you should get your local browser started up automatically, pointing to the address http://localhost:8100/, with an output similar to the one on the image below (I resized the window for clarity – if you’re using Chrome, you can get the Window Resizer plugin, or use the Chrome Dev Tools Emulate feature):

Awesome thing about this is that you have automatically set up live reload feature, which means that as soon as you change the code in your app folder, the application will reload automatically so that you don’t have to keep pressing the F5 (&#8984;+R) key on your Windows (Mac) machine.

If you like, you can get this project on Github.

Conclusion

In this chapter we’ve gone through the options that you have in making an app these days. Then we explained what actually is Ionic framework and how to install it on both Mac and Windows. With the use of the Ionic CLI we started a project based on the sidemenu template, and finally, we ran it locally in the browser with the use of ionic serve command. In the next chapter, I’ll show you how to create your own calculator application by making use of Ionic Creator.

How to get started with @Ionicframework 3 on #Mac and #Windows https://t.co/DZrp4q5ott pic.twitter.com/SbGfTbXzh0

— Nikola Brežnjak (@HitmanHR) July 16, 2017

Ionic3

How to create the simplest TODO application with Ionic 3

TL;DR

This is the simplest example which shows how to create a simple TODO application with Ionic 3 in just a few lines of code.

Quickstart

To see it in action:

  • Clone the finished project from Github
  • Make sure you’ve got the newest Ionic CLI (see this post for more instructions)
  • Run ionic serve
  • The app in action (after adding few items and swiping to delete one):

Step by step on how to create this yourself from scratch

Create a new blank Ionic project with ionic start Ionic3ServerSendTest blank

Template

Copy the following code to src/pages/home/home.html file:

Here we have three parts:

  • an input (ion-input) field where we enter the text for our TODO. We’ve put a ngModel of name todo on it – we will be able to reference this in the code by this same variable name.
  • a button (ion-button) which when clicked calls the function called add, which we’ll define in our src/pages/home/home.ts file shown below.
  • a list (ion-list) with multiple items (ion-item) in it. Also, we’ve made use of the ion-item-sliding (learn more about it from the docs here). We are repeating the ion-item-sliding component as many times as we have items in the todos array (you’ll see where we set that in the home.ts file, as mentioned above).

Code

To the src/pages/home/home.ts file copy the following content:

import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';

@Component({
    selector: 'page-home',
    templateUrl: 'home.html'
})
export class HomePage {
    todos: string[] = [];
    todo: string;

    constructor(public navCtrl: NavController) {

    }

    add() {
        this.todos.push(this.todo);
        this.todo = "";
    }

    delete(item) {
        var index = this.todos.indexOf(item, 0);
        if (index > -1) {
            this.todos.splice(index, 1);
        }
    }
}

The only thing that differs here from the basic blank template generated code is the todos and todo variables which we use for holding the array of todos and a current todo that’s connected to the model in the input box.

The add function pushes the current todo that we have in the input box at the time of pressing the Add button into the todos array.

The delete function first finds the index of the item that we want to delete from the list and then, by using the splice function, it deletes the item from the todos array.

Running the app

Just run ionic serve or even better yet ionic lab from the root directory of your Ionic app and you’ll have the app running locally in your browser tab with live reload option turned on.

Conclusion

That’s it. It doesn’t get any easier than this. Sure, this is as simple as it gets; there’s no persistence or anything, that’s for you to play with. Or, well, I may add that in the next tutorial…

‘Till then, have a great one, and a happy 4th of July to all my friends across the big pond 😉

How to create the simplest #TODO application with #Ionic 3 https://t.co/xvjmXVruBH

— Nikola Brežnjak (@HitmanHR) July 4, 2017

Ionic3

Posting data from Ionic 3 app to a PHP server

TL;DR

This is the simplest example which shows how to POST data from an Ionic 3 app to a PHP server.

The tutorial covering the Ionic version 1 can be found here, and the tutorial covering the Ionic version 2 can be found here.

Quickstart

To see it in action:

    1. Clone the finished project from Github
    2. Make sure you’ve got the newest Ionic CLI (see below for instructions)
    3. Run ionic serve
    4. You should see something like this:
      ionic2ServerPost

If you want to make it work from your server:

  1. Make sure you’ve got the newest Ionic CLI (see below for instructions)
  2. Clone the finished project from Github
  3. Upload the PHP/api.php file to your server
  4. In the src/pages/home/home.ts file adjust the link variable (line #21) to point to your server
  5. Run ionic serve

Getting started with Ionic 3

After neglecting Ionic 3 (and for the most part Ionic 2) for far too long due to the overburdening work I still have on my Ionic 1 apps, I finally got some time to take a look at Ionic 3 and update the most popular post about Ionic on my blog, so here you go and enjoy.

In general, from me playing just a bit with Ionic 3, I have to say I love it, so expect some more posts about it soon-ish…

To install the Ionic SDK and create Ionic 3 projects, you need to install the latest Ionic CLI:

npm install -g ionic

You don’t need to worry about this messing up your current ionic CLI since the new one still works with old Ionic 1 projects.

Just for reference, here’s what my ionic info says now:

$> ionic info 

global packages:

    @ionic/cli-utils : 1.4.0
    Ionic CLI        : 3.4.0

local packages:

    @ionic/app-scripts              : 1.3.7
    @ionic/cli-plugin-ionic-angular : 1.3.1
    Ionic Framework                 : ionic-angular 3.4.2

System:

    Node       : v8.0.0
    OS         : macOS Sierra
    Xcode      : Xcode 8.3.3 Build version 8E3004b 
    ios-deploy : 1.9.1 
    ios-sim    : 5.0.13 
    npm        : 5.0.1 

Step by step on how to create this yourself from scratch

  1. Create a new blank Ionic project with:
    ionic start Ionic3ServerSendTest blank
  2. Copy the following code to src/pages/home/home.html file:
    <ion-header>
     <ion-navbar>
     <ion-title>
     Ionic3 Server Send Test
     </ion-title>
     </ion-navbar>
    </ion-header>
    
    <ion-content padding>
     <ion-list>
     <ion-item>
     <ion-label floating>Username</ion-label>
     <ion-input type="text" name="username" [(ngModel)]="data.username"></ion-input>
     </ion-item>
    
     <button ion-button block (click)="submit()">Submit to server</button>
     </ion-list>
    
     <ion-card>
     <ion-card-header>
     Response
     </ion-card-header>
    
     <ion-card-content>
     <b>{{data.response}}</b>
     </ion-card-content>
     </ion-card>
    </ion-content>
    

    Here you basically created a form with an username input field and with a button which acts as a submit button.

    Once the button is clicked AngularJS should handle it within the submit() function which we will define in our src/pages/home/home.ts file (shown below).

    Input username uses  the new syntax for ng-model , and it binds to the variable data.username, so that you can then use it in your submit() function (shown below).

    Components are a bit different in Ionic 3 now, so I encourage you can take a look at the official documentation.

  3. On your server, create an api.php file with the following content:
    <?php
        //http://stackoverflow.com/questions/18382740/cors-not-working-php
        if (isset($_SERVER['HTTP_ORIGIN'])) {
            header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
            header('Access-Control-Allow-Credentials: true');
            header('Access-Control-Max-Age: 86400');    // cache for 1 day
        }
    
        // Access-Control headers are received during OPTIONS requests
        if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
    
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
                header("Access-Control-Allow-Methods: GET, POST, OPTIONS");         
    
            if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
                header("Access-Control-Allow-Headers:        {$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
    
            exit(0);
        }
    
    
        //http://stackoverflow.com/questions/15485354/angular-http-post-to-php-and-undefined
        $postdata = file_get_contents("php://input");
        if (isset($postdata)) {
            $request = json_decode($postdata);
            $username = $request->username;
    
            if ($username != "") {
                echo "Server returns: " . $username;
            }
            else {
                echo "Empty username parameter!";
            }
        }
        else {
            echo "Not called properly with username parameter!";
        }
    ?>

    As you can see from the code, the first part is explained in detail in this StackOverflow question, and it basically solves the CORS issue that you would otherwise run into.

    The second part, explained in detail in this StackOverflow question,  deals with the way you POST data from Ionic to your PHP server. The gist is that since we POSTed in a JSON format, we have to json_decode  the data that comes to your PHP server.

  4. To the file src/pages/home/home.ts file copy the following content and adjust the link variable to point to the file on your server:
    import { Component } from '@angular/core';
    import { NavController } from 'ionic-angular';
    import { Http } from '@angular/http'; //https://stackoverflow.com/questions/43609853/angular-4-and-ionic-3-no-provider-for-http
    
    @Component({
     selector: 'page-home',
     templateUrl: 'home.html'
    })
    
    export class HomePage {
     data:any = {};
    
     constructor(public navCtrl: NavController, public http: Http) {
     this.data.username = '';
     this.data.response = '';
    
     this.http = http;
     }
    
     submit() {
     var link = 'http://nikola-breznjak.com/_testings/ionicPHP/api.php';
     var myData = JSON.stringify({username: this.data.username});
     
     this.http.post(link, myData)
     .subscribe(data => {
     this.data.response = data["_body"]; //https://stackoverflow.com/questions/39574305/property-body-does-not-exist-on-type-response
     }, error => {
     console.log("Oooops!");
     });
     }
    }

    As with the Ionic 2 tutorial, things have changed a lot since Ionic 1, but in Ionic 3 (if you come from Ionic 2) you shouldn’t have any problems. Anyways, practice makes perfect, so make sure you put in the hours of deliberate practice.

    In this file, we import the Http component from Angular. You can check out the link in the comment to learn that you also need to import and inject HttpModule in src/app/app.module.ts (two new lines that I’ve added are bolded):

    import { BrowserModule } from '@angular/platform-browser';
    import { ErrorHandler, NgModule } from '@angular/core';
    import { IonicApp, IonicErrorHandler, IonicModule } from 'ionic-angular';
    import { SplashScreen } from '@ionic-native/splash-screen';
    import { StatusBar } from '@ionic-native/status-bar';
    import { HttpModule} from '@angular/http';
    
    import { MyApp } from './app.component';
    import { HomePage } from '../pages/home/home';
    
    @NgModule({
     declarations: [
     MyApp,
     HomePage
     ],
     imports: [
     BrowserModule,
     IonicModule.forRoot(MyApp),
     HttpModule
     ],
     bootstrap: [IonicApp],
     entryComponents: [
     MyApp,
     HomePage
     ],
     providers: [
     StatusBar,
     SplashScreen,
     {provide: ErrorHandler, useClass: IonicErrorHandler}
     ]
    })
    export class AppModule {}

    Inside the HomePage class, we now have a constructor where we’re setting some default values. Important to note, see how we’re passing in Http via the constructor parameter.

    Inside the submit function we use the http service to post to our API endpoint with some data. Make note of how we use the subscribe function to handle data once it arrives. Also, make sure you check out the StackOverflow link in the comment as a solution of how to access plain text response.

  5. Run ionic serve  from the root directory of your Ionic app

That’s all folks, I hope this tutorial helps you in starting your journey towards Ionic3 & Angular4!

Posting data from #Ionic 3 app to a #PHP server https://t.co/QYKiQtq1kJ

— Nikola Brežnjak (@HitmanHR) June 21, 2017

Recent posts

  • Discipline is also a talent
  • Play for the fun of it
  • The importance of failing
  • A fresh start
  • Perseverance

Categories

  • Android (3)
  • Books (114)
    • Programming (22)
  • CodeProject (35)
  • Daily Thoughts (77)
  • Go (3)
  • iOS (5)
  • JavaScript (127)
    • Angular (4)
    • Angular 2 (3)
    • Ionic (61)
    • Ionic2 (2)
    • Ionic3 (8)
    • MEAN (3)
    • NodeJS (27)
    • Phaser (1)
    • React (1)
    • Three.js (1)
    • Vue.js (2)
  • Leadership (1)
  • Meetups (8)
  • Miscellaneou$ (77)
    • Breaking News (8)
    • CodeSchool (2)
    • Hacker Games (3)
    • Pluralsight (7)
    • Projects (2)
    • Sublime Text (2)
  • PHP (6)
  • Quick tips (40)
  • Servers (8)
    • Heroku (1)
    • Linux (3)
  • Stack Overflow (81)
  • Unity3D (9)
  • Windows (8)
    • C# (2)
    • WPF (3)
  • Wordpress (2)

"There's no short-term solution for a long-term result." ~ Greg Plitt

"Everything around you that you call life was made up by people that were no smarter than you." ~ S. Jobs

"Hard work beats talent when talent doesn't work hard." ~ Tim Notke

© since 2016 - Nikola Brežnjak