/ ionic

Ionic 3 - Network Detection with Ionic Native

Have you ever been in a situation where you’ve been trying to do something on an application but you haven’t realised you’re offline? Or even worse, you're connected to the dreaded "lie-fi"? I bet your users have, and part of making smart mobile applications is about contextually knowing when the user is online or offline – this is where network detection within Ionic 3 comes in handy.

The application that we create will simply display a toast when the user goes online/offline. We’ll also be looking at RxJS and subscribing/unsubscribing to data streams.

Adding Plugins to the Project

Let's start off by making a new project and adding the Cordova/Ionic Native plugin(s):

# Create a new project
$ ionic start networkDetection blank

# Add Cordova/Ionic Native
$ ionic cordova plugin add cordova-plugin-network-information
$ npm install --save @ionic-native/network

Adding Network as a Provider

The next thing to do is add Network as a provider for our application. We'll then be able to inject Network into our component(s) and take advantage of the Ionic Native types.

import { Network } from '@ionic-native/network';
 
@NgModule({
  //...
  providers: [
    Network
  ]
})
export class AppModule {}
Component

For the purposes of this article, I’m adding this to my HomePage, but for a scalable implementation I’d recommend adding it to a provider.

We’ll be using Network for determining the network connection, ToastController to display a message to the user, and the NavController for navigation (the reason for which is detailed later in the article). Let’s inject them inside our component:

import { NavController, ToastController } from 'ionic-angular';
import { Network } from '@ionic-native/network';
 
@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {
 
  constructor(private toast: ToastController, private network: Network, public navCtrl: NavController) {
  }
}
Online/Offline Status

I’ll be hooking into the ionViewDidEnter() lifecycle to get access to the network status when the HomePage view is entered.

Both onConnect() and onDisconnect() return an Observable data stream. The benefit of observables in comparison to promises are that observables provide a stream for as long as we’ve subscribed to the event, whereas promises return a value in a .then() , but only once.

ionViewDidEnter() {
  this.network.onConnect().subscribe(data => {
    console.log(data)
  }, error => console.error(error));
 
  this.network.onDisconnect().subscribe(data => {
    console.log(data)
  }, error => console.error(error));
}

Using the subscription, we can then display this information in the console any time the network changes. The result looks something like this:

To improve this, I’ve opted to display a message to the user whenever they connect or disconnect.

Network Changes

Whenever the network state changes, the plugin updates a property named type which determines how the user is connected (i.e. wifi, 4g, 3g, and so on). A great thing about this is that we don’t have to do anything to get the update, it’s updated automatically upon observation.

We can therefore make a variable named networkType to keep track of the network state and display it along with our connectionState (i.e. online/offline) within our subscription(s).

I’ve made a function that encompasses this and displays a toast:

displayNetworkUpdate(connectionState: string){
  let networkType = this.network.type;
  this.toast.create({
    message: `You are now ${connectionState} via ${networkType}`,
    duration: 3000
  }).present();
}

Our ionViewDidEnter() then looks like this:

ionViewDidEnter() {
  this.network.onConnect().subscribe(data => {
    console.log(data)
    this.displayNetworkUpdate(data.type);
  }, error => console.error(error));
 
  this.network.onDisconnect().subscribe(data => {
    console.log(data)
    this.displayNetworkUpdate(data.type);
  }, error => console.error(error));
}

Now we're displaying a message to the user on connection change:

Improvements

If we created a Settings page and navigated to that page, we’d still get the toast when our network changes because we have yet to unsubscribe. This isn't optimal because we’d have subscription events firing from the HomePage throughout the rest of our application, so we’d need to unsubscribe from the event.

To unsubscribe from the observable, we’d have to create a variable to hold our subscriptions by firstly importing the Subscription type from RxJS:

import { Subscription} from 'rxjs/Subscription';`

We can then make variables within our HomePage of type Subscription:

export class HomePage {
 
  connected: Subscription;
  disconnected: Subscription;
...
}

Which allows us to then update our ionViewDidEnter() hook:

ionViewDidEnter() {
  this.connected = this.network.onConnect().subscribe(data => {
    console.log(data)
    this.displayNetworkUpdate(data.type);
  }, error => console.error(error));
 
  this.disconnected = this.network.onDisconnect().subscribe(data => {
    console.log(data)
    this.displayNetworkUpdate(data.type);
  }, error => console.error(error));
}

We’re now able to reference our subscriptions by variables, which means we can use both the subscribe() (as seen above) and unsubscribe() methods.

ionViewWillLeave(){
  this.connected.unsubscribe();
  this.disconnected.unsubscribe();
}

When leaving the view, we’ve unsubscribed from the observable, and our event will no longer fire outside of this page.

Conclusion

Using the Ionic Native Network plugin, we can gain access to network events from within your application. Want access to more specific Ionic Native content? Get the Udemy course with tons of implementations available here.

Paul Halliday

Progress Telerik Developer Expert. Course author with students in 110+ countries. BSc (Hons) Computer Science @ UoS. Google accredited Mobile Site professional.

Read More