Checking network status on Ionic application


#1

I have written the following service which attempts to check for the connectivity of an application, as in my Ionic app, I need to perform certain actions based on whether user is offline or online. Currently I am experiencing 3 problems.

  1. On my desktop, when testing in the browser, I always get an You are not connected message even when my wifi is not work. How can I get it to display the right message on my desktop?

  2. On my mobile, I’ve tested this and yes it does work initially onload and sets the connection status correctly but if I switch on/off my wifi connection it does not refresh immediately and takes some time. How can I get it to update “real-time” on my mobile application.

connection.service.js

(function() {
    'use strict';

    angular
    .module('dingocv.services')
    .service('ConnectionService', ConnectionService)


    function ConnectionService($rootScope, $cordovaNetwork) {

    this.isOnline = function() {
      if(ionic.Platform.isWebView()) {
        return $cordovaNetwork.isOnline();
      } else {
        return navigator.OnLine;
      }
    }

    this.isOffline = function() {
      if(ionic.Platform.isWebView()) {
        return !$cordovaNetwork.isOnline();
      } else {
        return !navigator.OnLine;
      }
    }

    this.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);
      }
    }
    }

})();

search.controller.js

(function() {
    'use strict';

    angular
    .module('dingocv.controllers')
    .controller('SearchController', SearchController)


    function SearchController($scope, CategoryService, ConnectionService) {

        if(ConnectionService.isOnline()){
            $scope.connected = true;
        } else {
            $scope.connected = false;
        }

        CategoryService.getCategoryList().then(function(dataResponse) {
            $scope.categories = dataResponse.data;
        });
    }

})();

search.view.html

<ion-view view-title="Search">
    <ion-content>
    <div ng-show="!connected">
        You are not connected
    </div>
    <div ng-show="connected">
        You are connected
    </div>
    </ion-content>
</ion-view>