Post

How to install & use Cordova Native Plugin in Ionic

Cordova wraps native code (for Android, iOS or browser) into a JavaScript interface which acts as a bridge to our code. Through this bridge, we can create plugins that give us access to native functionalities like camera from our JavaScript code without ever seeing or touching the native languages (unless we need to write our […]

   
How to install & use Cordova Native Plugin in Ionic

Cordova wraps native code (for Android, iOS or browser) into a JavaScript interface which acts as a bridge to our code. Through this bridge, we can create plugins that give us access to native functionalities like camera from our JavaScript code without ever seeing or touching the native languages (unless we need to write our own Cordova plugins).

Ionic apps are created and developed primarily through the Ionic command line utility (the “CLI”), and use Cordova to build/deploy. Ionic accesses the native functionality of the platforms through Cordova plugins and in order to access Cordova plugin Ionic has provided a list of the wrappers which are maintained by Ionic team, list of all these packages can be found at https://ionicframework.com/docs/enterprise.

In order to access Cordova native plugin functionality in ionic-4 angular some basic steps for each plugin are needed. For this example, we will install Cordova geolocation plugin to check user location from time to time, for details about the functionality provided by the plugin you can check the plugin on github. Follow the steps below for installing the plugin in Ionic for Angular :

1) Install plugin for Cordova through which Cordova access the native functionality

ionic cordova plugin add cordova-plugin-geolocation

2) Install wrapper plugin for Ionic

npm install @ionic-native/geolocation

3) Import the Ionic wrapper into your main module i.e app.module.ts

import { Geolocation } from '@ionic-native/geolocation/ngx';

4) Add the imported service to the providers array of the module

providers: [ Geolocation ]

5) Now to use this functionality in a component import the service and use the functionality above

construct(private geolocation: Geolocation) {}
                 ngOnInit() {
                                 this.geolocation.watchPosition().subscribe((data) => {
                                                 console.log(data.coords.latitude + '-' + data.coords.longitude);
                                 });
                 } 

 


I hope you like this tutorial. Let us know if you need help in Ionic app development.