Monitoring

Monitoring Online and Offline States in an Ionic 1.x Application



·

The ability to pull in data from the Internet is something many mobile applications rely on. Mobile devices don’t always have access to the Internet though, so we need to make sure that our applications either continue to work offline or at least display an appropriate error message to the user.

If you’ve designed your application to work online but haven’t tested it in offline mode, there’s probably a pretty good chance that it won’t fail gracefully. If you’ve integrated Google Maps for example you will receive an error since the google object won’t be available, which will break your application.

Detecting Internet Connectivity

We can detect if the user has an Internet connection through a normal desktop browser by using:

navigator.onLine

which will return true if an Internet connection is available and false if it is not. When using a Cordova application though it is better to use the Network Information plugin to detect if a connection is available (this also allows you to get more specific information as well if you need it).

Since we can’t access Cordova plugins when running through a desktop browser (i.e. whilst we are developing and testing the application) we will use both of these methods depending on which environment we are running in.

Another issue is that it’s possible that a user has an Internet connection when they start the application, but lose that connection later. So we need to be able to detect when there is a change in the network status (which we can do both with the network plugin and without it).

In this tutorial I’m going to walk you through how to set up and use the Network Information plugin in conjunction with the normal navigator.onLine method, how to detect online and offline states, and also how to detect when a device switches from online to offline or vice versa.

Installing the Network Information Plugin

Before we install the Network Information plugin, let’s set up ngCordova. If you do not know what ngCordova is or how to install it, take a look at this tutorial first.

Once you’ve got ngCordova up and running, you can continue with this tutorial.

Install the Network Information plugin by running the following command in your Ionic application

cordova plugin add cordova-plugin-network-information

Using the Network Information Plugin

Now that’s installed we will be able to detect whether the user is online or not by using:

$cordovaNetwork.isOnline(); 

when running on a device, and:

navigator.onLine;

when running through a browser. If you try to use the $cordovaNetwork.isOnline() method when the application is not running on a device then you will get an error. We can also detect when the user goes online or offline by using the following code:

      // listen for Online event
      $rootScope.$on('$cordovaNetwork:online', function(event, networkState){
        doSomething();
      });

      // listen for Offline event
      $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
        doSomething();
      });

when running on a device, or:

      window.addEventListener("online", function(e) {
        doSomething();
      }, false);    

      window.addEventListener("offline", function(e) {
        doSomething();
      }, false);  
    }

when running through the desktop browser.

What you do with this largely depends on what your application does, but you will want this to trigger some process in your application that will stop anything that relies on an Internet connection. If you are using Google Maps for example, you would want this code to disable the map and indicate to your users that they are not connected to the Internet (I will be releasing a tutorial on exactly how to do this soon).

Once you detect that the user has come back online again, you should reenable everything.

Creating a Connectivity Monitor Service

The differences between detecting on a device and detecting through a normal device browser is a bit of a pain. During development you are going to do a lot of testing through the browser so you want this to be as easy as possible. So instead of constantly checking what environment the app is running in, we can create a factory to make things easier for us.

Create the following factory in your application

.factory('ConnectivityMonitor', function($rootScope, $cordovaNetwork){

  return {
    isOnline: function(){
      if(ionic.Platform.isWebView()){
        return $cordovaNetwork.isOnline();    
      } else {
        return navigator.onLine;
      }
    },
    isOffline: function(){
      if(ionic.Platform.isWebView()){
        return !$cordovaNetwork.isOnline();    
      } else {
        return !navigator.onLine;
      }
    },
    startWatching: function(){
        if(ionic.Platform.isWebView()){

          $rootScope.$on('$cordovaNetwork:online', function(event, networkState){
            console.log("went online");
          });

          $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
            console.log("went offline");
          });

        }
        else {

          window.addEventListener("online", function(e) {
            console.log("went online");
          }, false);    

          window.addEventListener("offline", function(e) {
            console.log("went offline");
          }, false);  
        }       
    }
  }
})

Now we have a consistent way to check whether the device is online or offline, and it doesn’t matter what environment it is running in. You would simply just run:

ConnectivityMonitor.isOnline()

anywhere within your application that the ConnectivityMonitor has been injected and it will run the appropriate method. All this code does is check if the application is running inside of a Web View by using ionic.Platform.isWebView(), if it is running inside of a WebView then we know we are running through something like Cordova and thus are on a device. Otherwise, we assume that we are just on a normal desktop browser.

We’ve also created a startWatching function in the ConnectivityMonitor that will listen for the correct online and offline events.

How your app behaves offline is something that can slip your mind as you’re developing an application, but it’s really important to make sure you are handling it correctly (I know I’ve had an app rejected by Apple in the past because my app broke when the user was offline!).

What to watch next...

  • Afrim A.

    Hi, firstly thanks for the great tutorials and I wish you more success and great work in the future. Secondly I have one project in which I’m working to and it is about online radio streaming and I use html5 audio player to stream the radio. What I want to achieve is checking for Online/Offline events so if the user lost connection and reconnect again to trigger Play function automatically but this function with the Online/Offline states which I implemented like in the tutorial doesn’t seems to work when the app is background or device is locked. Is there anyway to listen for these events on those scenarios (app is minimized/in background or device is locked)?

    • snowbreez

      Looking at the same issue. It works in android. Did you get any solution for iOS

  • Pingback: Part 3: Advanced Google Maps Integration with Ionic and Remote Data | HTML5 Mobile Tutorials | Ionic, Phaser, Sencha Touch & PhoneGap()

  • Pingback: 170 Ionic Framework Resources()

  • Pingback: 200+ Ionic Framework Resources | Yahaay CodeStash()

  • sylfree9999

    Hi, firstly I would like to thank you for this great tutorial. Secondly I have one simple question, how can I stop loading some external scripts if I lost the network connection?

  • 文壮 刘

    Thanks for this great tutorial. But I wonder how to excute functions in every single controller when the network events fired? Thank you very much.

  • Victor Carvalho

    How I can do this on Ionic 2?

  • Great one. But how can I watch the startWatching() function from a controller?

  • mustiey

    can you please give me example how to inject ConnectivityMonitor.isOline() in my application. for instance in $http.get

  • For some reason I am getting `false` result even though the phone is connected to internet. Not only that, getNetwork() also gives “unknown” result. I wonder if this is to do with ionic run android command and whether I need to install the app with adb.

    Any ideas @joshmorony:disqus ?

    • KB

      What I find when I switch between Android and IOS, the syntax are slightly different. Could that be a problem?

  • KB

    Hi Josh, I wonder if you can help me with this. I have been using network plugin for a while, and it works great until recently. Maybe I try to find reason for why my network keeps dropping every few minutes. I tested my internet connection whenever my app was offline, I found other apps are working fine. Is there a work I can work out why my network is going offline?

    • Jacques De Villiers

      What device do you find this happens on? I am getting a similar thing on Android.

      • KB

        Hi Jacques,

        I use iPhone 6 Plus, and recently I work on a new app. I found the network plugin doesn’t work consistently on simulators. Help update me when you find any solutions to this. Still learning how everything is.

        Cheers

      • Jacques De Villiers

        So it looks like there is a bug in that plugin for Android, that sometimes it will report a user having no connection, when they are actually on wifi. So I have added a ‘ping’ endpoint that will double check whether the user really has no connection.

        You can look at a simple ping check to your server, however use it sparingly since if you overuse it will have a negative effect on battery performance.

      • KB

        Thank you, Jacques, sorry for this very late reply, have been busy working on other project until recently. Keep up with the great job you are doing here, appreciate it.

  • Thank you. For great tutorial.

  • Luis Perez

    Great tutorial, Thanks!

  • susendra

    Thank You so much, it’s working greate

  • uttam ojha

    “TypeError: Cannot read property ‘type’ of undefined..
    I will get this error when i run into android device

    • Divyanshu Tandon

      Same Error I am getting. Any help ?

  • Muthu Palani

    ionic.Platform.isWebView() is not working on device

  • Srikrishna Nunna

    When i am running in iOS Device(iOS 10.0, IPhone 6S) its not working. Plesae help.

  • Can i have the same implementation for ionic 2? Thanks though