You've successfully subscribed to developer.school
Great! Next, complete checkout for full access to developer.school
Welcome back! You've successfully signed in.
Success! Your account is fully activated, you now have access to all content.
Success! Your billing info is updated.
Billing info update failed.

Ionic 5: Network Detection with Capacitor

Paul Halliday
Paul Halliday

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"?

Here's a video version of this article! :)

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 5 using Capacitor 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.

Project Setup

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

# Initialise capacitor
$ ionic integrations enable capacitor
$ npx cap init network com.your.app

# Serve project
$ ionic serve

Android users

If you're wanting to use this on Android, you'll need to ensure that you add the following to AndroidManifest.xml:

<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />

Our demo will be Web based, but every other platform should work out of the box.

Network Detection

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

We’ll be using Network for determining the network connection, and then depending on the current network state (i.e. online or offline), we'll change the colour of the toolbar.

import { Component, OnInit, OnDestroy } from '@angular/core';
import { Plugins, NetworkStatus, PluginListenerHandle } from '@capacitor/core';

const { Network } = Plugins;

@Component({
  selector: 'app-home',
  templateUrl: 'home.page.html',
  styleUrls: ['home.page.scss'],
})
export class HomePage implements OnInit, OnDestroy {
  networkStatus: NetworkStatus;
  networkListener: PluginListenerHandle;

  async ngOnInit() {
    this.networkListener = Network.addListener('networkStatusChange', (status) => {
      console.log("Network status changed", status);
      this.networkStatus = status;
    });

    this.networkStatus = await Network.getStatus();
  }

  ngOnDestroy() {
    this.networkListener.remove();
  }
}

Let's understand what's going on here:

  1. We're importing Network from the Capacitor Plugins.
  2. We're using Network.addListener to listen on networkStatusChange, giving us the ability to log out the updated status.
  3. As when we start the application for the first time there likely hasnt been a change in network, we're grabbing the current status with Network.getStatus().
  4. Finally, we're removing the listener with .remove() whenever this component is destroyed.

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

Changing the Toolbar Colour

This gives us the power to change the Toolbar colour based on the current connection status. In order to do this, bind on the color attribute like so:

<ion-toolbar [color]="networkStatus && networkStatus.connected ? 'primary' : 'dark'">

We can also display information about the connection status in the template if we wanted to:

<ion-header>
  <ion-toolbar [color]="networkStatus && networkStatus.connected ? 'primary' : 'dark'">
    <ion-title>
      Network Detection
    </ion-title>
  </ion-toolbar>
</ion-header>

<ion-content>
  <div class="ion-padding">
    <h1>Connection status: {{networkStatus && networkStatus.connected ? "Online" : "Offline"}}</h1>
    
    <p>See more Ionic content at <a href="https://developer.school">developer.school</a></p>
  </div>
</ion-content>

Here's what this looks like:

Conclusion

That's how we can get information about the current Network connection with Ionic 4 and Capacitor. This works across iOS, Android, Web and Electron and is all thanks to Capacitor!

Ionic

Paul Halliday

👋 Want to see more content? Head over to the YouTube channel: https://youtube.com/c/paulhalliday!