Wednesday, August 22, 2018

How to check network connection in ionic 2 | ionic 3

Check network availability in ionic 




Why we should use network connection check?
If your app is using internet connectivity then, in this case, this is a very important check. With the help of this plugin, we can find is an internet connection is available on device or not. In this post, we will show an alert of "No Network Connection" if internet connection is not available on the device. This is very easy to implement. Just follow the below steps to implement this :

First, we need to add "Network" plugin in our project by using below command -

$ ionic cordova plugin add cordova-plugin-network-information
$ npm install --save @ionic-native/network

Now add this plugin in your app's module 

import { Network } from '@ionic-native/network';

providers: [
    Network,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]


Now just import plugin on your page where you want to check network connection -

import { Network } from '@ionic-native/network';
import { NavController, AlertController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(private network: Network, public alertCtrl: AlertController,public navCtrl: NavController) {
  if (this.checkNetwork()) {
  // This will call when network avaiable
}
else {
  // This will call when network is not available
  this.showNetworkError();
}
  }

  checkNetwork() {
    if (this.network.type != "none") {
        return true;
    }
    else {
        return false;
    }
  }

 showNetworkError() {
    let alertVar = this.alertCtrl.create({
        title: 'Error!',
        subTitle: 'No Network Connection',
        buttons: ['OK']
    });
    alertVar.present();
 }

}


With the help of above code, you can check network connection in the ionic app. Just check with your app. All the best 👍


If you want to check network connection type, You can check with the help of the below function

    checkNetwork() {
        this.platform.ready().then(() => {
            var networkState = this.network.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 alertVar = this.alertCtrl.create({
                title: "Connection Status",
                subTitle: states[networkState],
                buttons: ["OK"]
            });
            alertVar.present();
        });
    }


We can also subscribe network connect check, With this, we can manage network state changes (Online / Offline) at the same time -

import { Network } from '@ionic-native/network';

constructor(private network: Network) { }



Check below code to watch the network connection -

// watch the network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
  console.log('network connected!');
  // We just got a connection
  setTimeout(() => {
    if (this.network.type === 'wifi') {
      console.log('we got a wifi connection, woohoo!');
    }
  }, 3000);
});


// watch the network for a disconnect
let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
  console.log('network was disconnected :-(');
});


// stop connect watch
connectSubscription.unsubscribe();

// stop disconnect watch
disconnectSubscription.unsubscribe();

3 comments:

  1. how do i implement this my ionic 3.9 using worpress api

    ReplyDelete
    Replies
    1. Hey Sam,
      This is not dependent on WP api. This is for all apis. You can implement this at the time of api calling.

      Delete
  2. This is a really informative knowledge, Thanks for posting this informative Information. In House App

    ReplyDelete