Click here to Skip to main content
15,884,388 members
Articles / Programming Languages / Javascript

Check Network Information Change with Ionic Framework

Rate me:
Please Sign up or sign in to vote.
5.00/5 (2 votes)
15 Aug 2015CPOL4 min read 22.5K   5   4
Check network information change with Ionic framework

TL;DR

In this tutorial, I’m going to quickly show you how to get network information change with Ionic framework. What do I mean by network information change? Well, if you need to detect when your phone gets on the Internet, or loses connection, you can do so with this example code. Additionally, you can get the type of the network your phone is connected to (WIFI for example).

Finished Project

You can clone the finished project from Github: https://github.com/Hitman666/IonicNetworkInfo, and you can see how it actually looks like on the image below (nothing fancy, this is a test project after all ;)):

networkInfoIonic

Step By Step On How To Make This Yourself

Here are the quick steps in recreating the exact same app:

  1. Start a new Ionic project by doing:
    ionic start IonicNetworkInfo blank
  2. Then, change the directory to the newly created IonicNetworkInfo:
    cd IonicNetworkInfo
  3. Install ngCordova with Bower:
    bower install ngCordova
    If by some chance you don’t have bower installed, you can install it with npm:
    npm install bower -g
    <!--If you want to learn more about Bower, you can take a look at the tutorial I wrote for DigitalOcean Getting started with Bower.-->
  4. Open up the www/index.html file in your favorite editor, and add the reference to ngCordova (just above the cordova.js script):
    <!-- This is what you should add, the cordova below you'll already have -->
    <script src="lib/ngCordova/dist/ng-cordova.min.js"></script>
    
    <!-- cordova script (this will be a 404 during development) -->
    <script src="cordova.js"></script>
  5. Install the ngCordova network plugin by executing the following command in your Terminal/Command prompt (you should do this from the root directory of your app; so, in our case the IonicNetworkInfo directory):
    cordova plugin add org.apache.cordova.network-information

    To check if you have successfully installed the plugin, you can run the following command (from the root directory – I won’t be repeating this anymore; when I say you should run some command from the Terminal/Command prompt that, in this case, means from the root directory of the application):

    cordova plugin list

    You should see the following output:

    > cordova plugin list                                                                                                                           
    com.ionic.keyboard 1.0.4 "Keyboard"
    org.apache.cordova.network-information 0.2.15 "Network Information"
  6. Open up the www/js/app.js file and add ngCordova to the dependencies list, so that basically the first line looks like this:
    angular.module('starter', ['ionic', 'ngCordova'])
  7. Create a new controller in the www/js/app.js file called MyCtrl, with the following content:
    JavaScript
    .controller('MyCtrl', function($scope, $cordovaNetwork, $rootScope) {
        document.addEventListener("deviceready", function () {
    
            $scope.network = $cordovaNetwork.getNetwork();
            $scope.isOnline = $cordovaNetwork.isOnline();
            $scope.$apply();
            
            // listen for Online event
            $rootScope.$on('$cordovaNetwork:online', function(event, networkState){
                $scope.isOnline = true;
                $scope.network = $cordovaNetwork.getNetwork();
                
                $scope.$apply();
            })
    
            // listen for Offline event
            $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
                console.log("got offline");
                $scope.isOnline = false;
                $scope.network = $cordovaNetwork.getNetwork();
                
                $scope.$apply();
            })
    
      }, false);
    })
    In this controller, you attach an event listener on the deviceready event (because it could be that the device would not have been yet initialized when this code runs) and you get the network information with:
    JavaScript
    $cordovaNetwork.getNetwork();
    The information, about whether you’re connected to the internet is obtained with the following line:
    JavaScript
    $scope.isOnline = $cordovaNetwork.isOnline();
    Then, you register two events, $cordovaNetwork:online and $cordovaNetwork:online which trigger when the device gets online/offline. In them, you then just update the $scope variables ().

    Just for reference, the whole content of the www/js/app.js file should be:

    JavaScript
    // Ionic Starter App
    
    // angular.module is a global place for creating, registering and retrieving Angular modules
    // 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
    // the 2nd parameter is an array of 'requires'
    angular.module('starter', ['ionic', 'ngCordova'])
    
    .run(function($ionicPlatform, $cordovaNetwork, $rootScope) {
      $ionicPlatform.ready(function() {
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if(window.cordova && window.cordova.plugins.Keyboard) {
          cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        }
        if(window.StatusBar) {
          StatusBar.styleDefault();
        }
      });
    })
    
    .controller('MyCtrl', function($scope, $cordovaNetwork, $rootScope) {
        document.addEventListener("deviceready", function () {
    
            $scope.network = $cordovaNetwork.getNetwork();
            $scope.isOnline = $cordovaNetwork.isOnline();
            $scope.$apply();
            
            // listen for Online event
            $rootScope.$on('$cordovaNetwork:online', function(event, networkState){
                $scope.isOnline = true;
                $scope.network = $cordovaNetwork.getNetwork();
                
                $scope.$apply();
            })
    
            // listen for Offline event
            $rootScope.$on('$cordovaNetwork:offline', function(event, networkState){
                console.log("got offline");
                $scope.isOnline = false;
                $scope.network = $cordovaNetwork.getNetwork();
                
                $scope.$apply();
            })
    
      }, false);
    });
  8. In the index.html file, inside the ion-content tag, paste the following content:
    HTML
    <div class="card">
                    <div class="item item-text-wrap">
                        <h1>Network: {{network}}</h1>
                    </div>
                </div>
    
    
                <div class="card">
                    <div class="item item-text-wrap">
                        <ion-toggle ng-model="isOnline" ng-checked="item.checked">
                            <h1 ng-show="isOnline">I'm online</h1>
                            <h1 ng-show="! isOnline">I'm offline</h1>
                        </ion-toggle>
                    </div>
                </div>

    Basically, what we do here is we show the contents of the network variable (which is attached to the $scope via the controller). Also, by using the ion-toggle component, we show the “I’m online” / “I’m offline” notifications.

    Just for reference, the content of the whole index.html file should look like this:

    HTML
    <!DOCTYPE html>
    <html>
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content="initial-scale=1, 
        maximum-scale=1, user-scalable=no, width=device-width">
        <title></title>
    
        <link href="lib/ionic/css/ionic.css" rel="stylesheet">
        <link href="css/style.css" rel="stylesheet">
    
        <!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
        <link href="css/ionic.app.css" rel="stylesheet">
        -->
    
        <!-- ionic/angularjs js -->
        <script src="lib/ionic/js/ionic.bundle.js"></script>
    
        <script src="lib/ngCordova/dist/ng-cordova.min.js"></script>
        <!-- cordova script (this will be a 404 during development) -->
        <script src="cordova.js"></script>
    
        <!-- your app's js -->
        <script src="js/app.js"></script>
    </head>
    <body ng-app="starter" ng-controller="MyCtrl">
    
        <ion-pane>
            <ion-header-bar class="bar-stable">
                <h1 class="title">Ionic Blank Starter</h1>
            </ion-header-bar>
          
            <ion-content padding="true">
                <div class="card">
                    <div class="item item-text-wrap">
                        <h1>Network: {{network}}</h1>
                    </div>
                </div>
    
                <div class="card">
                    <div class="item item-text-wrap">
                        <ion-toggle ng-model="isOnline" ng-checked="item.checked">
                            <h1 ng-show="isOnline">I'm online</h1>
                            <h1 ng-show="! isOnline">I'm offline</h1>
                        </ion-toggle>
                    </div>
                </div>
    
            </ion-content>
        </ion-pane>
    </body>
    </html>

Testing Time

In order to test this application, you should run it on your device (because you can’t disable network in iOS simulator).

First, in case you haven’t, add the desired platform (execute this command from the root of the directory). For iOs, execute:

ionic platform add ios

Or, for Android, execute:

ionic platform add android

Just a quick note – in order to build the app for iOs, you need to be running this on Mac machine (sure, there are ways around it, but TBH, I’m not a fan of them). As for Android, you can normally run it on your Windows machine (if, of course you have all the SDKs in place. I’ll write about setting these up in another tutorial, so will update the link here when the post will be published, for those who want to see this kind of information).

If you have an Android device plugged to your computer (and all the SDKs in place), you can run the following two commands to get your application running on your Android device:

ionic build android && ionic run android

To get this application running on your iOS device, you first have to build the application, and you can do this by executing the following command:

ionic build ios

Now, open up the IonicNetworkInfo/platforms/ios folder and you should see the following content:

Screen Shot 2015-08-15 at 11.52.18

Next, open up IonicNetworkInfo.xcodeproj file with Xcode:

Make sure that your iOS device is connected to your Mac computer, select it from the dropdown menu and click run:

XcodeRun

Now, experiment with the application by turning your WIFI on/of, turning your Cellular network (if you have it) on/off, and basically enjoy seing the information change automatically :). Surely, you can do way more advanced stuff based on this simple example, but I hope this will get you started…

That’s all folks, I hope this will prove to be useful to someone. If you have any questions, or you’ve noticed some blatant blunder that I may have made, please don’t hesitate to share it in the comments, I’ll make sure to reply promptly.

The post Check network information change with Ionic framework appeared first on Nikola Brežnjak blog.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Software Developer (Senior)
Croatia Croatia
I’m an engineer at heart and a jack of all trades kind of guy.

For those who care about titles, I hold a masters degree in computing from FER (and a black belt in karate, but that’s another story…).

During the last years, worked in a betting software industry where I made use of my knowledge in areas ranging from full-stack (web & desktop) development to game development through Linux and database administration and use of various languages (C#, PHP, JavaScript to name just a few).

Currently, I’m a senior software engineer at TelTech, where we make innovative communications apps, and I <3 it.

Lately, I’m very passionate about Ionic framework and am currently in the top 3 answerers on StackOverflow in Ionic framework. I wrote a book about Ionic framework which you can get for free on Leanpub: Ionic framework – step by step from idea through prototyping to the app stores.

Other technical writing:

+ wrote a book Getting MEAN with MEMEs
was a technical reviewer for a book Deploying Node published by Packt
was a technical reviewer for a book Getting started with Ionic published by Packt
After writing 300 posts, this is why I think you should start blogging too

Come and see what I write about on my blog.

Comments and Discussions

 
QuestionHow ask to turn on network? Pin
MoPHL4-Sep-15 6:48
professionalMoPHL4-Sep-15 6:48 
AnswerRe: How ask to turn on network? Pin
Nikola Breznjak4-Sep-15 12:39
professionalNikola Breznjak4-Sep-15 12:39 
Well, simply you would first check if the user is connected to the internet. If not, then show him a "loading screen" until he connects to the internet. For prompting the user you can use the $ionicLoading service: http://ionicframework.com/docs/api/service/$ionicLoading/[^]
Come and see what I write about on my blog.

My book on MEAN stack.

GeneralRe: How ask to turn on network? Pin
MoPHL4-Sep-15 22:18
professionalMoPHL4-Sep-15 22:18 
GeneralRe: How ask to turn on network? Pin
Nikola Breznjak4-Sep-15 22:24
professionalNikola Breznjak4-Sep-15 22:24 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.