Sunday, December 16, 2018

Failed to find 'ANDROID_HOME' environment variable



I am getting below error when I am trying to run project -

> cordova build android
Android Studio project detected
(node:15997) UnhandledPromiseRejectionWarning: Unhandled promise rejection (rejection id: 1): Failed to find 'ANDROID_HOME' environment variable. Try setting it manually.
Failed to find 'android' command in your 'PATH'. Try update your 'PATH' to include path to valid SDK directory.


To resolve this issue please run below commands in the terminal -

export ANDROID_HOME="/Users/chetandeshmukh/Library/Android/sdk"
export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/tools:$PATH"


How to find the Android SDK path?

First open android studio, Then click on SDK manager. For more info please check below image -



Now select Appearance & Behavior -> System Settings -> Android SDK



 Now copy your SDK location with the help of the above steps and update in command.


This process will set the Android Home path in your system.


Now try once again to run your project. This process will resolve your problem. If you still facing any issue please add your error in the comment section. We will resolve this. 

Sunday, December 9, 2018

Ionic round progressbar



To integrate this first we need to install the below module with the help of npm :

npm install angular-svg-round-progressbar --save

After installing this you need to import the RoundProgressModule in your module file :

import {NgModule} from '@angular/core';
import {RoundProgressModule} from 'angular-svg-round-progressbar';

@NgModule({
  imports: [RoundProgressModule]
})


Now in your page TS file add below lines -

export class RatePage {

  public selectedRange=0;

  
  constructor(public navCtrl: NavController) {

}

  close(){
    alert(this.selectedRange)
  }

  save(){
    alert(this.selectedRange)
  }

}


Now add below code in your html file -

<div class="main_box">
<div class="box">

 <div class="current">{{ selectedRange }}/{{ 100 }}</div>
 <round-progress
 [current]="selectedRange"
 [max]="100"
 [color]="'#45ccce'"
 [background]="'#eaeaea'"
 [radius]="80"
 [stroke]="20"
 [semicircle]="false"
 [rounded]="true"
 [clockwise]="true"
 [responsive]="false"
 [duration]="800"
 [animation]="'easeInOutQuart'"
 [animationDelay]="0"></round-progress>


<ion-range min="0" max="100" [(ngModel)]="selectedRange" color="secondary">
 <ion-label range-left>0</ion-label>
 <ion-label range-right>100</ion-label>
</ion-range>


<ion-row class="row">
 <ion-col class="col" col-6="">
     <button (click)="save()" class="login-btn button button-md button-default button-default-md" ion-button="" type="submit"><span class="button-inner">Submit
     </span><div class="button-effect"></div></button>
 </ion-col>
 <ion-col class="col" col-6="">
   <button (click)="close()" class="login-btn button button-md button-default button-default-md" ion-button="" type="submit"><span class="button-inner">Cancel
   </span><div class="button-effect"></div></button>
</ion-col>
</ion-row>


</div>

</div>


Add below code in your CSS file -

.scroll-content{
    padding: 0px !important;
}
.box{ margin: 0% 5%; padding: 0px 10px; font-size: 1.4rem; height: 60%; background-color: #fff; opacity: 1 !important; margin-top: 20%; border: 1px solid gray; }

round-progress{
    margin: 20% 25% 0% 25%;
}
.main_box{
    height: 100%;
}
[col-6]{
    text-align: center;
}
.range-md .range-knob, .range-ios .range-knob{
    width: 30px;
    height: 30px;
}
.range-md .range-bar, .range-ios .range-bar{
    top: 28px;
}
.label-md, .label-ios{ margin-top: 16px !important;}
.current {
    position: absolute;
    margin: 34% 25% 0% 35%;
    font-weight: 400;
    font-size: 2rem;
}


You can check more details on below link, also other options are available on below link -
https://github.com/crisbeto/angular-svg-round-progressbar

Check below demo link -
http://crisbeto.github.io/angular-svg-round-progressbar

Tuesday, November 27, 2018

Could not find play-services-tasks-license.aar (com.google.android.gms:play-services-tasks-license:11.8.0)



Could not find play-services-tasks-license.aar (com.google.android.gms:play-services-tasks-license:11.8.0).
Searched in the following locations:
    https://jcenter.bintray.com/com/google/android/gms/play-services-tasks-license/11.8.0/play-services-tasks-license-11.8.0.aar


Please follow below steps to solve this issue:-


Go to build.gradel 



and replace this -

buildscript {
    repositories {
        mavenCentral()
        jcenter()
    }
}

with this -

buildscript {
    repositories {
        google()
        mavenCentral()
        jcenter()
    }
}


And replace this - 

allprojects {
    repositories {
        mavenCentral();
        jcenter()
    }
}


With this -

allprojects {
    repositories {
        google()
        mavenCentral();
        jcenter()
    }
}



Now - Click on “Sync Now”



If you again face this issue - 

A problem occurred evaluating root project 'android'. > Could not find method google() for arguments [] on repository container of type org.gradle.api.internal.artifacts.dsl.DefaultRepositoryHandler.


To resolve this issue add this line in your gradel file -

dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }


If you are having this issue in react native app. Please use this below lines in your gradel file -


buildscript {
    repositories {
        jcenter()
        google()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:3.0.1'
    }
}
allprojects {
    repositories {
        mavenLocal()
        jcenter()
        maven {
// All of React Native (JS, Obj-C sources, Android binaries) is installed from npm
            url "$rootDir/../node_modules/react-native/android"
        }
        google()
    }
}




Make sure to sync your project after doing all this. This will resolve your issue.

Thursday, November 8, 2018

ionic interview questions



Ionic interview questions  OR hybrid mobile app interview questions -

1. What is Ionic Framework?
The IONIC framework is an HTML5 platform that allows web developers (UI developer) to build hybrid mobile applications. Hybrid apps are those apps that have all access of native perform functionality and or you can say it is small websites running in browser shell in the application. It is a powerful HTML5 SDK that helps peoples to build mobile apps using HTML, CSS, and JavaScript. Ionic framework mainly focus on the look and feel of the app and its UI interaction. Ionic very fits well with the front end part of your app. It is free to use under MIT license so that it can be used for personal or commercial applications/projects.


2. What are the advantages and disadvantages of building hybrid/mobile applications using the Ionic framework?
The most obvious advantages are:
1. The ionic framework builds hybrid applications using web technologies. It means web developers can very easily build mobile applications too. Also, because it uses JavaScript / angular, almost the same codebase can be used to build both iOS and Android applications.
2. Development cost is less compared to native iOS and Android applications.
3. The ionic framework is excellent for quick application ideas prototyping.
Some of the disadvantages are:
4. It is not suited for high-end graphics dependent applications or games.
5. Performances are not as good as native applications, namely animations, scrolling, and network operations.
6. As mentioned, JavaScript animations are not as performant as native animations. However, there are JavaScript / angular libraries, like chartjs, which provide decent graph UI performance on the devices.


3. Explain what is the difference between "ionic build and ionic prepare” commands?
ionic prepare copies all files from the www folder into the target platform’s www folder.
ionic build also does this but also builds the app’s source code so that it can be run on a simulator/emulator or a device.


4. Explain some of Useful Ionic Commands. 
Please check commands and its description -
1. start-  This command is used to create a new project.
2. serve- This command is used to start a local dev server for app dev/testing.
3. generate-  This command is used to generate pipes, components, pages, directives, providers, and tabs.
4. docs - This command is used to open the Ionic documentation website.
5. build - This command is used to build web assets and prepare your app for any platform targets.
6. link- This command is used to connect your local app to Ionic.
7. info - This command is used to print system/environment info.
8. login- This command is used to log in with your Ionic ID.
9. signup - This command is used to create an Ionic account.
10. upload- This command is used to upload a new snapshot of your app.
11. telemetry-  This command is used to opt in and out of telemetry.
12. config set- This command is used to set config values.
13. config get- This command is used to print config values.
14. cordova compile- This command is used to compile native platform code.
15. cordova build- This command is used to build an Ionic project for a given platform.
16. cordova emulate- This command is used to emulate an Ionic project on a simulator or emulator.
17. cordova plugin - This command is used to manage Cordova plugins.
18. cordova platform- This command is used to manage Cordova platform targets.
19. cordova resources - This command is used to automatically create icon and splash screen resources.
20. cordova prepare - This command is used to copies assets to Cordova platforms, preparing them for native builds.
21. package download- This command is used to download your packaged app.
22. package build- This command is used to start a package build.
23. package list - This command is used to list your cloud builds.
24. cordova run - This command is used to run an Ionic project on a connected device.
25. package info - This command is used to get info about a build.


5. How to use service/providers in Ionic?
Services play a very important role in Ionic as you already know they provide information to our application and perform various tasks for us. SimpleAlert, data, ConnectivityMonitor, GoogleMaps, etc. are some of the services which are built in ionic framework. There are a few points which are to be kept in mind while creating a service. Adding a provider to it, Importing a service and injecting it is the most important thing. The services should be imported into the classes where they are going to be used. When it is injected inside a constructor, a new member variable is created which can be accessed from anywhere within the class. A provider can be added in a service by two ways - Either it can be added to an individual component, or it can be added globally to the application when bootstrapping the root component.


6. Explain the difference between PhoneGap, Cordova, and Ionic?
PhoneGap is a library that exposes native mobile phone functionalities as JavaScript API. When Adobe purchased PhoneGap, its open source core was donated to the Apache Software Foundation under the name Cordova. In the beginning, there was almost no difference between Cordova and PhoneGap. Although, over the years of development, Adobe started adding a proprietary set of the services to PhoneGap. Today, it is safe to say PhoneGap is Cordova plus extra Adobe services. Ionic uses Cordova, not PhoneGap for its core tools. Beside native mobile phone functionalities, Ionic gives structure and code scalability to JavaScript applications by using AngularJS. It also provides a set of Angular directives and components to speed up application development.


7. How to use observables in an Ionic framework?
Observables are something that is not specific to Ionic or Angular. It is provided by the RxJS library. Observables are almost similar to the promises but can do a lot more. It can deal with multiple values at a time rather than just resolving one value. You can even subscribe to an observable to manipulate the data which is associated with it. Observables are considered to be “lazy”, i.e. they won’t get executed until and unless they are subscribed to. Various operations can be applied to the observables for modifying it and returning a new one. You can even create your own observable. The observable patterns are combined into one with the help of the subject which is preferred for simple implementations.


8. What is Ionic Market?
The ionic market provides ready starter, plugins, themes etc. for the developer to download them and use for their own projects.


9. How do you persist data between application launches using the Ionic framework?
As Ionic behind the scene builds HTML5 based applications, you can use localStorage and sessionStorage API to persist data on the mobile phone. However, since localStorage can only store strings, objects need to be stringified before saving. Also, it is important to mention localStorage has size limit around 5MB.


10. How do you pass data from one view to another in Ionic applications?
You can use the NavController and NavParams to send data to pages that you push


11. Give some examples of hybrid mobile app frameworks?
re are several frameworks are available for hybrid mobile app development.

Mobile Angular UI
Intel XDX
PhoneGap
Ionic
Appcelerator Titanium
Kendo UI


12. How can you render a 5000 item list in Ionic, without affecting scroll performance?
Ionic provides a collection-repeat directive that renders only visible items in the DOM. So even if the list is huge, like 5000 in our example, only items visible in a viewport are rendered. Thus, scroll performance is not affected.


13. How To Generating New Pipes, Tabs, Components and Pages using Ionic 3 and Angular 4?
Ionic 3 CLI Commands For Angular 4 Projects
1.     Pipes,
2.     Providers and
3.     Directives,
4.     Components,
5.     Tabs

Syntax –
-        ionic generate [pipes] [pipes-name]
-        ionic generate [providers] [providers-name]
-        ionic generate [directives] [directives-name]
-        ionic generate [components] [components-name]
-        ionic generate [tabs] [tabs-name]

Example –
-        ionic generate pipe
-        ionic generate provider
-        ionic generate directive
-        ionic generate component
-        ionic generate tabs
-        ionic generate page

-        ionic generate component demoApp
-        ionic generate page Login
-        ionic generate page register --no-module
-        ionic generate page users --constants
-        ionic generate pipe MyCustomPipe


14. What is the advantage of caching the views in Ionic apps? Provide examples.
Ionic by default caches up to ten views, which improves performance and also maintains different states in the views at the same time. For example - The cache can maintain scroll position in the views or active state of buttons.


15. What is the difference between native mobile app design and responsive web design? Do we really need both? Explain.
Mobile apps can be developed natively or as hybrid apps, while mobile-friendly websites can be developed as adaptive or responsive. The basic design process behind all of them is more or less the same. The only thing we need to consider when designing for mobile is that we have a specific set of rules we need to follow. Apple has its own, and so does Google.
When you’re designing for iOS or Android, the underlying process is the same. First, we do research that will outline best practices and show us what we can do on a certain platform and what not. Basically, research helps us we learn restrictions and take advantage of possibilities a given field.
Designers are likely to work on both native app and responsive web designs. Native apps are important because we want the user to have them on their dashboard, and this way we want to help users in their everyday activities. Some native apps can work offline while others can’t.
Responsive web design is important for SEO and Google indexing. So, if we want to have your project well-ranked on Google, you definitely go for a mobile-friendly responsive design.


Monday, October 15, 2018

iPhone XR / XS / XS Max CSS media queries



Handling the Notch on iPhone X / XR / XS / XS Max OR iPhone media queries for responsive design  -

Media queries are very useful to modify your website or hybrid apps depending on a device resolution/type. This is very important to manage resolution in different devices. It help us to present batter view of app/website to users. Below are the examples for iPhone XR / XS / XS Max CSS media queries -


/* Apple iPhone XR 1792x828px at 326ppi Media Queries */
@media only screen 
    and (device-width : 414px) 
    and (device-height : 896px) 
    and (-webkit-device-pixel-ratio : 2) { }

/* Apple iPhone XS 2436x1125px at 458ppi Media Queries */
@media only screen 
    and (device-width : 375px) 
    and (device-height : 812px) 
    and (-webkit-device-pixel-ratio : 3) { }

/* Apple iPhone XS Max 2688x1242px at 458ppi Media Queries */
@media only screen 
    and (device-width : 414px) 
    and (device-height : 896px) 
    and (-webkit-device-pixel-ratio : 3) { }


Below are the examples for iPhone X / 8 / 8 Plus CSS media queries -

/* Apple iPhone X Media Queries */
@media only screen 
    and (device-width : 375px) 
    and (device-height : 812px) 
    and (-webkit-device-pixel-ratio : 3) { }

/* Apple iPhone 8 Media Queries */
@media only screen 
    and (device-width : 375px) 
    and (device-height : 667px) 
    and (-webkit-device-pixel-ratio : 2) { }

/* Apple iPhone 8 Plus Media Queries */
@media only screen 
    and (device-width : 414px) 
    and (device-height : 736px) 
    and (-webkit-device-pixel-ratio : 3) { }



Note : If you are looking for a specific orientation. Follow below rules -

For portrait orientation add below rule :

    and (orientation : portrait) 


For landscape orientation add below rule :

    and (orientation : landscape) 



Now use above media query in your project. It helps me a lot. If you have any query please post in a comment. 

For other all Media Queries please check this link - https://allexperts16.blogspot.com/2018/06/media-queries-for-standard-devices.html

It has Media Queries for - iPads, iPad 3, iPhone 4, iPhone 5, iPhone 6, iPhone 6+, Samsung Galaxy S3, Samsung Galaxy S4, Samsung Galaxy S5, and many more. 


Wednesday, October 10, 2018

How to remove white space from iPhone X in ionic / Cordova

Hey all,

Please check below image in this you can find this issue -




Finally, I found the solution to this problem. It saves a lot of time. Now UI is proper of my app. Please run below command in your project -

First uninstall "statusbar" old version plugin by using this command -
ionic cordova plugin rm cordova-plugin-statusbar

Now add the new version of this plugin by using this command -
$ ionic cordova plugin add cordova-plugin-statusbar
$ npm install --save @ionic-native/status-bar


Basically, what we did, We just removed the plugin and added new updated plugin of "Status Bar". This solves my problem. Please check this image -







Steps for ionic soluion :

ionic cordova plugin rm cordova-plugin-statusbar
$ ionic cordova plugin add cordova-plugin-statusbar
$ npm install --save @ionic-native/status-bar


Steps for Cordova solution :

cordova plugin rm cordova-plugin-statusbar
cordova plugin add https://github.com/apache/cordova-plugin-statusbar.git


Tuesday, October 2, 2018

How to generate APNS certificate for iOS Push Notifications

APNS (Apple Push Notification Service) is a platform service which is created by Apple Inc. This service enables developers to send push notifications in iOS devices. For this, you must have a Paid Apple Developer. Please follow below steps to create .p12 certificate require to send push notifications -


1. First login in your apple developer account by using this URL: https://developer.apple.com/account/



2. Now select "Certificates" from the left menu. Click on the "+" button from the right.



3. Now select “Apple Push Notification service SSL (Production)” and click “Continue” button -



4. Now, select the app ID from Drop down list and click on “Continue” -



5. Now we need to create CSR. To create CSR follow the steps under “About Creating a Certificate Signing Request (CSR)” -



6. Now upload ".certSigningRequest" file which you have generated (in Step 5), then click on "Generate" button -



7. Now click on "Done" to finish the registration process, The page will be refreshed and you will able to see the download option for this -


After downloading the certificate just double click on downloaded file. This will add the certificate in your keychain access. 

8. Now open “Keychain” in your system, look for the certificate you have just installed in step 7. If you are not sure which certificate that was - That should start with “Apple Production IOS Push Services” and followed by app’s bundle ID.




9. Now, Expand the certificate, you should able to see the private key with your name or your company name. Select both items by using the "Select" key on your keyboard. Now right click and choose “Export 2 items” -



Then save this p12 file with a valid name like "pushcert.p12" to your Desktop. Now you will be prompted to enter a password to protect this p12 file, You can select skip the password or enter a password option.

10. Now open the terminal and move in your directory where you have this p12 file. Run below command to generate pem file -

openssl pkcs12 -in pushcert.p12 -out pushcerts.pem -nodes -clcerts



Tuesday, September 4, 2018

How to crop image in Ionic 2 | Ionic 3 | Ionic 4




Image Cropping : Hello friends! In this post, we will learn how to crop the image in ionic. This is very simple to implement. You just need to have knowledge about Camera and Crop plugin.


For this, we need 2 plugins (Camera and Crop)

Install Camera plugin :
$ ionic cordova plugin add cordova-plugin-camera
$ npm install --save @ionic-native/camera

Now, Install Crop plugin:
$ ionic cordova plugin add cordova-plugin-crop
$ npm install --save @ionic-native/crop


Now, Please use below code in your TS file to crop image -

import { Crop } from '@ionic-native/crop';
import { Camera, CameraOptions } from '@ionic-native/camera';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html',
  providers: [Camera, Crop]
})

export class HomePage {

public base64Image:any;

constructor(private camera: Camera, private crop: Crop) {

  }


   selectImageFromCamera()
 {
   const options: CameraOptions = {
     quality: 100,
     targetWidth: 1000,
     targetHeight: 1000,
     destinationType: this.camera.DestinationType.FILE_URI,
     encodingType: this.camera.EncodingType.JPEG,
     mediaType: this.camera.MediaType.PICTURE
   }
   
   this.camera.getPicture(options).then((imageData) => {
    // imageData is either a base64 encoded string or a file URI
    // If it's base64:
    //this.base64Image = 'data:image/jpeg;base64,' + imageData;
    this.base64Image = imageData;

    this.crop.crop(this.base64Image, {quality: 100})
    .then(
      newImage => {
       this.base64Image=newImage;
        console.log('new image path is: ' + newImage);
 
       },
      error => {
        console.error('Error cropping image', error);

      }
    );

   }, (err) => {
    // Handle error
   });


 }

}


Now, Read below points for step by step explanation of the above code :

First, you need to import "Crop and Camera, CameraOptions" by using the below code :

import { Crop } from '@ionic-native/crop';
import { Camera, CameraOptions } from '@ionic-native/camera';


Add this to the constructor by using below code :

constructor(private camera: Camera, private crop: Crop) {

}


Now you need to call selectImageFromCamera() function when you want to trigger crop event with the help of the camera. In this function first, we are capturing image from the camera -

const options: CameraOptions = {
quality: 100,
targetWidth: 1000,
targetHeight: 1000,
destinationType: this.camera.DestinationType.FILE_URI,
encodingType: this.camera.EncodingType.JPEG,
mediaType: this.camera.MediaType.PICTURE
}

this.camera.getPicture(options).then((imageData) => {
// imageData is either a base64 encoded string or a file URI
// If it's base64:
//this.base64Image = 'data:image/jpeg;base64,' + imageData;
this.base64Image = imageData;

}, (err) => {
// Handle error
});


Now after capturing image from camera we will crop this image by using below code :

this.crop.crop(this.base64Image, {quality: 100})
.then(
newImage => {
this.base64Image=newImage;
console.log('new image path is: ' + newImage);

},
error => {
console.error('Error cropping image', error);

}
);


This is the process to crop the image in ionic.

Wednesday, August 29, 2018

Migrating of an existing application from Ionic 3 to 4

Migrating of Ionic 3 Project to Ionic 4


What is ionic: Ionic is an open source UI toolkit for building performant, high-quality mobile and desktop apps using web technologies (HTML, CSS, and JavaScript).

Ionic Framework always focus on frontend user experience. It’s easy to learn and integrates nicely with other libraries or frameworks, such as Angular. Currently, Ionic Framework has official integration with Angular, but its support for Vue and React are in development.

migration from ionic 3 to 4 is very straightforward. 

Migrating from Ionic 3 to 4: You need to follow below steps to migrating an existing application from Ionic 3 to 4.Steps are follows -


Before this please make sure the you have latest version of Node.js and npm are installed on your system.

- First, Install the latest version of Ionic

$ npm install -g ionic

The -g means it is a global install.


- Now create a new project using the blank template -

$ ionic start myApp blank --type=angular


- Project structure : 



- Copy your ionic 3 Angular services from src/providers to src/app/services

Services should include { providedIn: 'root' } in the @Injectable() decorator. For details, please review Angular provider docs. https://angular.io/guide/providers


- Copy the app's other root level items (pipes, components, etc) of your ionic 3, Keep in mind that the project directory structure has been changed from src/components to src/app/components, etc.

- Now copy your ionic 3 global Sass styling from src/app/app.scss to src/global.scss

- Copy the rest of the application, page by page or feature by feature, keeping the following items in mind:

  1. Emulated Shadow DOM is turned on by default.
  2. Page/component Sass should no longer be wrapped in the page/component tag and should use Angular's styleUrls option of the @Component decorator.
  3. RxJS has been updated from v5 to v6.
  4. Certain lifecycle hooks should be replaced by Angular's hooks.


 - Including third-party modules: If your v3 application depends upon third-party modules like moment etc., make sure to install them in the v4 project too.

Breaking Changes: Check this URL for more information (https://github.com/ionic-team/ionic/blob/master/angular/BREAKING.md#breaking-changes)


A list of the breaking changes introduced to each component in Ionic Angular v4 -

Action Sheet
Alert
Back Button
Button
Chip
Colors
Content
Datetime
Dynamic Mode
FAB
Fixed Content
Grid
Icon
Infinite Scroll
Item
Item Divider
Item Options
Item Sliding
Label
List Header
Loading
Menu
Menu Toggle
Modal
Nav
Navbar
Option
Overlays
Radio
Range
Refresher
Scroll
Segment
Select
Spinner
Tabs
Text / Typography
Theming
Toolbar

Wednesday, August 22, 2018

How to check network connection in ionic 2 | ionic 3

Check network availability in ionic 




Why we should use network connection check?
If your app is using internet connectivity then, in this case, this is a very important check. With the help of this plugin, we can find is an internet connection is available on device or not. In this post, we will show an alert of "No Network Connection" if internet connection is not available on the device. This is very easy to implement. Just follow the below steps to implement this :

First, we need to add "Network" plugin in our project by using below command -

$ ionic cordova plugin add cordova-plugin-network-information
$ npm install --save @ionic-native/network

Now add this plugin in your app's module 

import { Network } from '@ionic-native/network';

providers: [
    Network,
    {provide: ErrorHandler, useClass: IonicErrorHandler}
  ]


Now just import plugin on your page where you want to check network connection -

import { Network } from '@ionic-native/network';
import { NavController, AlertController } from 'ionic-angular';

@Component({
  selector: 'page-home',
  templateUrl: 'home.html'
})
export class HomePage {

  constructor(private network: Network, public alertCtrl: AlertController,public navCtrl: NavController) {
  if (this.checkNetwork()) {
  // This will call when network avaiable
}
else {
  // This will call when network is not available
  this.showNetworkError();
}
  }

  checkNetwork() {
    if (this.network.type != "none") {
        return true;
    }
    else {
        return false;
    }
  }

 showNetworkError() {
    let alertVar = this.alertCtrl.create({
        title: 'Error!',
        subTitle: 'No Network Connection',
        buttons: ['OK']
    });
    alertVar.present();
 }

}


With the help of above code, you can check network connection in the ionic app. Just check with your app. All the best 👍


If you want to check network connection type, You can check with the help of the below function

    checkNetwork() {
        this.platform.ready().then(() => {
            var networkState = this.network.type;
            var states = {};
            states[Connection.UNKNOWN]  = 'Unknown connection';
            states[Connection.ETHERNET] = 'Ethernet connection';
            states[Connection.WIFI]     = 'WiFi connection';
            states[Connection.CELL_2G]  = 'Cell 2G connection';
            states[Connection.CELL_3G]  = 'Cell 3G connection';
            states[Connection.CELL_4G]  = 'Cell 4G connection';
            states[Connection.CELL]     = 'Cell generic connection';
            states[Connection.NONE]     = 'No network connection';
            let alertVar = this.alertCtrl.create({
                title: "Connection Status",
                subTitle: states[networkState],
                buttons: ["OK"]
            });
            alertVar.present();
        });
    }


We can also subscribe network connect check, With this, we can manage network state changes (Online / Offline) at the same time -

import { Network } from '@ionic-native/network';

constructor(private network: Network) { }



Check below code to watch the network connection -

// watch the network for a connection
let connectSubscription = this.network.onConnect().subscribe(() => {
  console.log('network connected!');
  // We just got a connection
  setTimeout(() => {
    if (this.network.type === 'wifi') {
      console.log('we got a wifi connection, woohoo!');
    }
  }, 3000);
});


// watch the network for a disconnect
let disconnectSubscription = this.network.onDisconnect().subscribe(() => {
  console.log('network was disconnected :-(');
});


// stop connect watch
connectSubscription.unsubscribe();

// stop disconnect watch
disconnectSubscription.unsubscribe();