Our website is made possible by displaying online advertisements to our visitors. Please consider supporting us by disabling your ad blocker.

Determine Network Availability In An Ionic 2 Mobile App

Continuing to freshen up my popular Ionic Framework tutorials in preparation for the release of Ionic 2, I figured it was time to revisit how to determine network availability in an application. Previously I showed how to check for a network connection using Ionic Framework 1, but this time it makes sense to do the same using Ionic 2.

We’ll use the same Apache Cordova Network Information plugin from the previous tutorial, but this time we’ll evaluate how to use it with Angular.

Let’s first start by creating a new Ionic 2 project. Using your Terminal (Mac and Linux) or Command Prompt (Windows), execute the following commands:

ionic start ExampleProject blank --v2
cd ExampleProject
ionic platform add ios
ionic platform add android

Two important things to note. If you’re not using a Mac, you cannot add and build for the iOS platform. You must also be using the Ionic CLI that supports building Ionic Framework 2 applications.

With our project created, we need to add the Apache Cordova plugin for determining the network status. This can be done by executing the following in your Command Prompt or Terminal:

cordova plugin add cordova-plugin-network-information

We’re now ready to look at some code!

To keep the project simple we’re only going to look at two files. First, open your project’s app/pages/home/home.ts file and change it too look like the following:

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

declare var navigator: any;
declare var Connection: any;

@Component({
    templateUrl: 'build/pages/home/home.html'
})
export class HomePage {

    constructor(private navCtrl: NavController, private platform: Platform) { }

    checkNetwork() {
        this.platform.ready().then(() => {
            var networkState = navigator.connection.type;
            var states = {};
            states[Connection.UNKNOWN]  = 'Unknown connection';
            states[Connection.ETHERNET] = 'Ethernet connection';
            states[Connection.WIFI]     = 'WiFi connection';
            states[Connection.CELL_2G]  = 'Cell 2G connection';
            states[Connection.CELL_3G]  = 'Cell 3G connection';
            states[Connection.CELL_4G]  = 'Cell 4G connection';
            states[Connection.CELL]     = 'Cell generic connection';
            states[Connection.NONE]     = 'No network connection';
            let alert = Alert.create({
                title: "Connection Status",
                subTitle: states[networkState],
                buttons: ["OK"]
            });
            this.navCtrl.present(alert);
        });
    }

}

Much of this was taken from the plugin documentation, but let’s go over it anyways.

In the first line we include the Platform and Alert dependencies because with Platform we can check the readiness of an Apache Cordova plugin and with Alert we can use slick alerts. In the constructor we define those two dependencies to be used through the particular page.

Before we look at the constructor method, notice the following two lines:

declare var navigator: any;
declare var Connection: any;

For the first part of this guide we’re using vanilla Apache Cordova in our application. It does not have TypeScript type definitions. To eliminate the compiler errors we must first tell the compiler to ignore these two variables.

Now for where the magic happens.

In the checkNetwork function we first make sure the application is ready to use plugins. When it is, we determine the connection type and check what it means using our states map. The final step is showing an alert with the human readable status.

This brings us to the UI for our page. Open your project’s app/pages/home/home.html file and change the code to the following:

<ion-header>
    <ion-navbar>
        <ion-title>
            Ionic Network Check
        </ion-title>
    </ion-navbar>
</ion-header>

<ion-content padding>
    <button (click)="checkNetwork()">Check Network</button>
</ion-content>

Nothing fancy here. We are just showing a button and when it is clicked it launches the checkNetwork function from our HomePage class.

Now let’s say you wanted to use Ionic Native instead of the vanilla Apache Cordova way of doing plugins. Going back to the TypeScript file, add the following to the list of imports:

import {Network} from "ionic-native";

With Ionic Native, we no longer need to declare the two Apache Cordova variables. To use this, check out the new checkNetwork function:

checkNetwork() {
    this.platform.ready().then(() => {
        let alert = Alert.create({
            title: "Connection Status",
            subTitle: <string> Network.connection,
            buttons: ["OK"]
        });
        this.navCtrl.present(alert);
    });
}

Notice we are using Network to determine things. We are also casting the connection value to a string to prevent TypeScript compiler errors.

Conclusion

Determining the status of our network is not too difficult of a task. We saw how to do it in Ionic Framework 1, and it isn’t much different in Ionic 2 because it uses the same plugin. The plugin itself offers much more than what I demonstrated so if you need to work with listeners and other cool stuff, check out the official documentation on the subject.

A video version of this article can be seen below.

Nic Raboy

Nic Raboy

Nic Raboy is an advocate of modern web and mobile development technologies. He has experience in Java, JavaScript, Golang and a variety of frameworks such as Angular, NativeScript, and Apache Cordova. Nic writes about his development experiences related to making web and mobile development easier to understand.