Cordova - PhoneGap

From Sinfronteras
Jump to: navigation, search

https://cordova.apache.org/

https://phonegap.com

Apache Cordova/PhoneGap enables software programmers to build applications for mobile devices using CSS3, HTML5, and JavaScript instead of relying on platform-specific APIs like those in Android, iOS, or Windows Phone. It enables wrapping up of CSS, HTML, and JavaScript code depending upon the platform of the device. It extends the features of HTML and JavaScript to work with the device. The resulting applications are hybrid, meaning that they are neither truly native mobile application (because all layout rendering is done via Web views instead of the platform's native UI framework) nor purely Web-based (because they are not just Web apps, but are packaged as apps for distribution and have access to native device APIs).


Is PhoneGap equal to Cordova? https://www.businessofapps.com/news/apache-cordova-adobe-phonegap-know-real-differences/

PhoneGap is a distribution of Apache Cordova. So Apache Cordova serves as the engine to power PhoneGap just like WebKit is an engine that powers Chrome and Safari (iOS browser). Nonetheless, as an app developer or as an organization, you don't have to worry about the differences between these two. The story is like this:

  • PhoneGap was previously a product of Adobe.
  • To keep it open-source always and follow standards, PhoneGap codebase was handed over to Apache.
  • At Apache, it got a name change as Cordova.
  • And now it’s better known as Apache Cordova.

The most important to understand here is that PhoneGap is powered by apache Cordova. PhoneGap is Cordova plus some extra Adobe stuff. If you are developing a hybrid mobile app, you can either create it using proper Cordova or choose Adobe's ecosystem for using PhoneGap distribution of Cordova.

The open-source Cordova/PhoneGap will be always free and delivered by Apache. Over time, Adobe may add values to this (current) codebase that consists of other Adobe services and that will be named as PhoneGap, which will be chargeable.



Contents

Installing Cordova

https://cordova.apache.org/docs/en/latest/guide/cli/


The Cordova command-line tool is distributed as an npm package.


  • Install Cordova with NPM:
sudo npm install -g cordova

The -g flag above tells npm to install cordova globally. Otherwise it will be installed in the node_modules subdirectory of the current working directory.


  • Check Cordova Version:
cordova --version


If you don't already have one. Following installation, you should be able to invoke git on your command line. The CLI uses it to download assets when they are referenced using a url to a git repo.



Creating and Setting the Cordova project environment

https://cordova.apache.org/docs/en/latest/guide/cli/



Create the App - Project folder

https://cordova.apache.org/docs/en/latest/guide/cli/

Execute the below command to create an «Cordova application environment» (Project folder):

cordova create myapp

or using the entire syntax:

cordova create path [id [name [config]]] [options]
cordova create hello com.example.hello HelloWorld


This creates the required directory structure for your cordova app. By default, the cordova create script generates a skeletal web-based application whose home page is the project's www/index.html file.



Add platforms

Now add the required platform in your application. This will create required files for the corresponding platform under the platforms/android and platforms/ios directories (may be necessary to use sudo):

cd myapp
cordova platform add ios
cordova platform add android
cordova platform add browser

If we want to test in the browser (using the command «cordova serve»), it is very important to add the browser platform. Otherwise, you will have some very annoying pop up messages (gap_init, for example) every time you refresh the browser.


Use below command to list the installed and available platforms for Cordova application:

cordova platform -ls


If you accidentally added any platform which you no longer needs, just remove that using commands like below:

cordova platform remove ios
cordova platform remove android



Preview your App

https://cordova.apache.org/docs/en/latest/reference/cordova-cli/#cordova-serve-command



Preview on the Web Browser

https://cordova.apache.org/docs/en/latest/reference/cordova-cli/#cordova-serve-command


At this point, you can just go to «.../www/index.html» to preview your App in the Web Browser.


You can also use the «cordova serve» command to run a local web server using specified port or default of 8000.

cordova serve

Then you can preview your App in the Web Browser at:

http://localhost:PORT/
http://localhost:8000/
  • Then, we have to choose the platform.


Or directly at:

http://localhost:PORT/PLATFORM/www
http://localhost:8000/android/www/


You shoul see something like this in the Web Browser:

Cordova hello world.png


Preview on a Mobile Device using PhoneGap CLI

http://docs.phonegap.com/getting-started/4-preview-your-app/cli/

You can use the PhoneGap CLI to immediately preview your app on a device without installing platform SDKs, registering devices, or compiling code. The PhoneGap CLI (using the command «phonegap serve») starts a small web server to host your project and returns the server address for you to pair with from the PhoneGap Developer App running on your mobile device.

phonegap serve



Structure of the Project folder - Some important files

By default, «cordova create» script generates a skeletal web-based application whose start page is the project's www/index.html file. Any initialization should be specified as part of the device ready event handler defined in www/js/index.js


Some important files in the project folder:

  • config.xml
Inside of the application code, there is a very simple file called config.xml that is used to tell your application which libraries it can use.


  • plugins folder
Here you can see a list of folders that each contain the tools for the different plugins.


  • The following are the file that we can start modifying to create our App
www/index.html
www/js/index.js
www/css/index.css


From www/index.html notice the following line:

<!--
Customize this policy to fit your own app's needs. For more guidance, see:
    https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy
Some notes:
    * gap: is required only on iOS (when using UIWebView) and is needed for JS->native communication
    * https://ssl.gstatic.com is required only on Android and is needed for TalkBack to function properly
    * Disables use of inline scripts in order to mitigate risk of XSS vulnerabilities. To change this:
        * Enable inline JS: add 'unsafe-inline' to default-src
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'self' data: gap: https://ssl.gstatic.com 'unsafe-eval'; style-src 'self' 'unsafe-inline'; media-src *; img-src 'self' data: content:;">

By default, this line said you can only load scripts from your own site (self). If we try to load a script from another site (www.google.com) this line would restricted it. That's the whole point of Content Security Policy (CSP). When we use API, for example, we need to modify this line so our project is able to access script from other sites. In the url provided in the comment of the above line (https://github.com/apache/cordova-plugin-whitelist/blob/master/README.md#content-security-policy), there are some example CSP declarations. However, what I have done to avoid problems, is to comment (or delete) this line. After do so, I didn't have restrictions problems. See https://stackoverflow.com/questions/37298608/content-security-policy-the-pages-settings-blocked-the-loading-of-a-resource/37308542



Building the Cordova App

By «Building» we mean to compile the source code and create the executable file to be installed in the device.



Install pre-requisites for building

To build and run apps, you need to install SDKs for each platform you wish to target. Alternatively, if you are using browser for development you can use browser platform which does not require any platform SDKs.

To check if you satisfy requirements for building the platform:

cordova requirements


Android platform requirements

https://cordova.apache.org/docs/en/latest/guide/platforms/android/index.html#requirements-and-support



Java Development Kit - JDK

See Java



Gradle
sudo apt install gradle



Android SDK


Installation:

  • Go to the Android Studio official page: https://developer.android.com/studio/index.html
  • Download and unzip the sdk-tools-linux zip file.
  • To complete the installation we need to add the paths of the bin folder to our PATH environment variable:

.bashrc

PATH=/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/tools:$PATH
PATH=/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/tools/bin:$PATH


  • We can also do it using apt. However, when I did id with apt, I was not able to find the sdkmanager command in my system. So I recommended to do it by downloading the zip file from the official page.
sudo apt install android-sdk



Adding SDK Packages:

After installing the Android SDK, you must also install the packages for whatever API level you wish to target. It is recommended that you install the highest SDK version that your version of cordova-android supports (see Requirements and Support).

Open the Android SDK Manager (Tools > SDK Manager in Android Studio, or sdkmanager on the command line), and make sure the following are installed:

  • Android Platform SDK for your targeted version of Android
  • Android SDK build-tools version 19.1.0 or higher
  • Android Support Repository (found under the "SDK Tools" tab)

See Android's documentation on Installing SDK Packages for more details: https://developer.android.com/studio/command-line/sdkmanager


Esta fue la parte más complicada. Si no se instalan los package necesarios en esta parte, la ejecución del comando «cordova requirements» no encontrará la instalación e «Android target». Esto creo que lo solucioné de esta forma:

sdkmanager "build-tools;29.0.0" "platform-tools" "platforms;android-28"



Setting environment variables

https://cordova.apache.org/docs/en/latest/guide/platforms/android/index.html#setting-environment-variables

Cordova's CLI tools require some environment variables to be set in order to function correctly. The CLI will attempt to set these variables for you, but in certain cases you may need to set them manually. The following variables should be updated:
  • Set the JAVA_HOME environment variable to the location of your JDK installation: See Java
  • Set the ANDROID_HOME environment variable to the location of your Android SDK installation:
export ANDROID_HOME=/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/
  • It is also recommended that you add the Android SDK's tools, tools/bin, and platform-tools directories to your PATH:
Al instalar Android SDK, el zip file sdk-tools-linux descargado de la página oficial, sólo contiene el directorio tools. No contiene ningún directorio platform-tools. Es por eso que es muy importante «Adding SDK Packages» como se describió arriba. A través de «sdkmanager» se isntalan los paquetes y adicionan los directorios correspondientes («android-sdk/platform-tools» and «android-sdk/build-tools») (https://cordova.apache.org/docs/en/latest/guide/platforms/android/index.html#setting-environment-variables):
export PATH=${PATH}:/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/platform-tools
export PATH=${PATH}:/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/build-tools
export PATH=${PATH}:/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/build-tools/29.0.0


Luego de todas las configuraciones realizadas en esta parte, se adicionaron las siguientes líneas al «/home/adelo/.bashrc» y «/root/.bashrc». Es muy importante señalar que las configuraciones las he colocado también en «/root/.bashrc» porque he tenido que ejecutar algunos comandos como root por cuestiones de permisología («cordova build android», por ejemplo).

«/home/adelo/.bashrc» & «/root/.bashrc»:

# Android SDK:
PATH=/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/tools:$PATH
PATH=/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/tools/bin:$PATH


# Cordova - Android platform requirements:
#* Set the ANDROID_HOME environment variable to the location of your Android SDK installation:
export ANDROID_HOME=/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/
#* It is also recommended that you add the Android SDK's tools, tools/bin, and platform-tools directories to your PATH:
export PATH=${PATH}:/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/platform-tools
export PATH=${PATH}:/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/build-tools
export PATH=${PATH}:/home/adelo/1-system/.1-conf-system/1-archivos_programas-ubuntu/android-sdk/build-tools/29.0.0



Build the App

On all requirements completed successfully, run the build command to build your application:

cordova build              ## Build all added platforms 
cordova build android      ## Build for specific platform

Antes de ejecutar el comando anterior, tuve que iniciar modo root: «sudo su». Luego: «cordova build android». A través de «sudo cordova build android» no fue posible ejecutar este paso con éxito.


The «cordova build» command is a shortcut for «cordova prepare» + «cordova compile» commands. It Allows you to build the app. This procedure will compile the code and build the executable file for the specific platform. In the case of an Android platform, it will build a .apk file.



Using Phonegap Build

https://build.phonegap.com/apps

This is an online service that we can use to build the App. If we don't have all the requirements (packages installed) in or computer to be able to build (compile) the App, we can use https://build.phonegap.com/apps. In this Web site, we can upload our code and it will build the App and return the executable file (.apk file in case of Android app).

We can also use Adobe® PhoneGap™ Build Web site to build our App. As is written in this Web Site, we just have to upload our HTML5, CSS, and JavaScript assets to the Adobe® PhoneGap™ Build cloud service and it do the work of compiling the code.



What is an APK File

An Android Package Kit (APK for short) is the package file format used by the Android operating system for distribution and installation of mobile apps. Just like Windows (PC) systems use an .exe file for installing software, the APK does the same for Android.



Test the App - Deploy the app on a device or emulator

https://cordova.apache.org/docs/en/latest/guide/cli/#test-the-app



On an emulators from Android Studio

cordova emulate android



On a physical device

https://developer.android.com/studio/run/device

https://developer.android.com/studio/command-line/adb.html#issuingcommands

cordova run
cordova run android

«cordova run» prepares, builds, and deploys app on specified platform devices/emulators. If a device is connected it will be used, unless an eligible emulator is already running.


Before «cordova run» we need:

  • To connect the device over a USB cable.


  • To set up the device for testing, following procedures that vary for each platform:
  • In my phone: Settings > Developper options: USB debugging (On)


  • To target the device using the adb command:
https://developer.android.com/studio/run/device
https://developer.android.com/studio/command-line/adb.html#issuingcommands
https://riptutorial.com/android/example/8560/direct-adb-command-to-specific-device-in-a-multi-device-setting


To display the list of devices attached:
adb devices  # Dispay devices connected by serial number


Then, to target a device by serial number (No estoy seguro si es realmente así que que debemos realizar el target de la divice):
adb -s <device> <command>
adb -s W3D7N16328008017 shell



Plugins


Adding plugins

https://cordova.apache.org/docs/en/latest/guide/cli/index.html#add-plugins

You can modify the default generated app to take advantage of standard web technologies, but for the app to access device-level features, you need to add plugins.

A plugin exposes a Javascript API for native SDK functionality. Plugins are typically hosted on npm. Some key APIs are provided by the Apache Cordova open source project and these are referred to as Core Plugin APIs. You can also use the CLI to launch the search page.

You can search for them on the plugin search page: https://cordova.apache.org/plugins/


To add a plugin, we can use the «cordova plugin add» command. For example:

cordova plugin add cordova-plugin-camera
Fetching plugin "cordova-plugin-camera@~2.1.0" via npm
Installing "cordova-plugin-camera" for android
Installing "cordova-plugin-camera" for ios

Plugins can also be added using a directory or a git repo.

The «cordova plugin add» command will add and save the corresponding plugin to config.xml and package.json.


to view currently installed plugins:

cordova plugin ls
// or
cordova plugin 



Vibration plugin

https://www.npmjs.com/package/cordova-plugin-vibration


Installation:

cordova plugin add cordova-plugin-vibration


This plugin defines global objects including navigator.vibrate.

Although in the global scope, they are not available until after the «deviceready» event:

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
    console.log(navigator.vibrate);
}


Vibrates the device for a given amount of time:

navigator.vibrate(time);
navigator.vibrate(3000);

time: Milliseconds to vibrate the device. (Number)


Example:

index.js
function shake(){
    navigator.vibrate(3000);
}


index.html
<!-- * Directly using the function provided by the Vibration plugin -->
<button onclick="navigator.vibrate(3000)"> Vibrate </button>
<!-- * Using the our function created in index.js, which implement navigator.vibrate(): -->
<button onclick="shake()"> Vibrate </button>



Camera plugin

https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-camera/


Installation:

This requires cordova 5.0+

cordova plugin add cordova-plugin-camera


This plugin defines a global navigator.camera object, which provides an API for taking pictures and for choosing images from the system's image library.

Although the object is attached to the global scoped navigator, it is not available until after the deviceready event:

document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
    console.log(navigator.camera);
}


Methods

  • camera.getPicture(successCallback, errorCallback, options) :

Takes a photo using the camera, or retrieves a photo from the device's image gallery. The image is passed to the successCallback as a Base64-encoded String, or as the URI for the image file.

We need to pass two callbackfunctions:

  • successCallback
  • errorCallback


Example:

In the HTML file:

Create a button to trigger the camera:

<button id="buttonPic" onclick="pics()" >Picture</button>


Create a place holder to display the picture:

<img id="myImage" height="50%" width="50%"> </img>


In the JS file:

Create the function that takes the picture:

function pics(){
    navigator.camera.getPicture(successCallback, errorCallback);
}


Create the successCallback function:

function successCallback(imageData){
   var image = document.getElementById('myImage');
   image.src = imageData;
}

If you want to take a photo using the web browser:

function successCallback(imageData){
    var image = document.getElementById('myImage');
    image.src = "data:image/jpeg;base64," + imageData;
}


Create the errorCallback function:

function errorCallback(){
    document.getElementById("errorCamera").innerHTML = "Error when trying to take a picture :(";
}



Geolocation plugin

https://cordova.apache.org/docs/en/latest/reference/cordova-plugin-geolocation/


Installation:

This requires cordova 5.0+ ( current stable 1.0.0 )

cordova plugin add cordova-plugin-geolocation


The function that this plugin provides to access the GPS sensor in your device is:

navigator.geolocation.getCurrentPosition(geoCallback, onError)


The functions «geoCallback» and '«onError»' are callback functions that will be called after.



Get the GPS reading from you device and print it in the console web browser

This first part is going to be done using the web browser.


  • Create a new function called getLocation() to wrap up the getCurrentPosition function provided above.
  • Create the geoCallback function:
  • It should take one attribute (position).
  • Print to the console the content of the position object.
  • Create the onError function
  • It should take one attribute (message).
  • Print to the console the content of the message object.
  • Create a button on the front end to call the getLocation function.
  • Run your app using your web browser, and inspect the page to see the result.


index.js

//* Create a new function called getLocation() to wrap up the getCurrentPosition function provided by the plugin:
function getLocation(){
    navigator.geolocation.getCurrentPosition(geoCallback, onError)
}

//* Create the geoCallback function:
function geoCallback(position){
    console.log(position);
}

//* Create the onError function:
function onError(message){
    console.log(message);
}


index.html

<!-- * Create a button to trigger: -->
<button id="geolocation" onclick="getLocation()"> GeoLocation </button>


After clicking the «GeoLocation» button you can go to the console web browser and the the Position that has been printed in the cosole. It should look like this:

GeolocationObject.png



Get the GPS reading from your device and print it in the web page

  • Create a place holder in the HTML file to display the GPS position.
  • Modify the geoCallback function to extract the data from the position object, and display on front end using the place holder created in part a.
  • TIP: The position object works as a JSON object, so we can access the latitude using position.coords.latitude
  • Make sure to display at least longitude and altitude.
  • Run your app using your web browser.
  • Run you app using your phone.


index.js

//* Create a new function called getLocation() to wrap up the getCurrentPosition function provided by the plugin:
function getLocation(){
    navigator.geolocation.getCurrentPosition(geoCallback, onError)
}

//* Create the geoCallback function:
function geoCallback(position){
    console.log(position);

    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    var lat_lon = "Latitud: "+latitude+"  ;  Longitude: "+longitude;
    document.getElementById("geoPlaceholder").innerHTML = lat_lon;
}

//* Create the onError function:
function onError(message){
    console.log(message);
}


index.html

<!-- * Create a button to trigger: -->
<button id="geolocation" onclick="getLocation()"> GeoLocation </button>
<!-- * Placeholder to to display the latitud and longitud -->
<div id="geoPlaceholder"> Display geolocation </div>



Some Cordova app examples

  • You can find a template to create your app from by seaching for the keyword cordova:template on npm


  • You can also use local templates on your computer, or a Git repository. This is, for instances, a github repository with some Cordova-phonegap examples:


  • UI Design Tutorial - Login, Blog app Phonegap:



Cordova app with bootstrap




AIPs


Google Maps JavaScript API

https://developers.google.com/maps/documentation/javascript/tutorial


Objectives:

  • Use the Google Map API to display a map in your application.
  • Add a marker to the map in a specific position
  • Use the reading of the GPS sensor (Using the Geolocation plugin) to pin point the location of the device on a Google Map.



Get our Google Map API key

Optional because the sample code provided includes the lecturer's API key. If you would like to create you own API key (which is recommended) you will need to sign up to use the Google Map API. The first year of use of the API is for free, but you will need a credit/debit card to sign up anyway.

  • Sign up to use the Google Maps API
  • Click on APIs and Services on the left menu
  • Click on “create project" and then click on "create".
  • Give your new project a name and click on "create".
  • Click on “Enable APIS and services".
  • Click on “Maps JavaScript APi" and then "Enable".
  • Click on “Credentials", then on “Create Credentials", and then on “API Key". Finally, copy your API Key and close the dialog.
  • The free version of this API is very limited, however, Google APIs will give you a trial with USD$300 bonus to use their full capabilities within a year, if you enable the billing. This should be plenty of credit to get you through this module.



Get a map displayed on your front end from Google Maps API

  • Add a place holder for your map in the HTML file of your app.
  • Add the script code to import the Google Map JavaScript API.
  • Notice that the callback function is initMap.
  • Include the initMap function in your JavaScript file
  • Add the style code to display the map properly in your CSS file
  • Run your app and to make sure your map appears.


index.html

<!--* Script code to import the Google Map JavaScript API -->
<!--** Notice that the callback function is initMap -->
<script async defer
    src="https://maps.googleapis.com/maps/api/js?key=YOUR_GOOGLE_KEY&callback=initMap">
</script>
<!-- * Placeholder to display the map -->
<div id="map"></div>


index.js

function initMap(){
    var cct = {lat: 53.346, lng: -6.2588};

    var map = new 
        google.maps.Map(document.getElementById('map'),
            {
                zoom: 4,
                center: cct
            }
        );
    
    var marker = new google.maps.Marker({
        position: cct,
        map: map
    });
}


index.css

#map {
    height: 400px;
    width: 100%;
}



Add another marker to the map in another position

function initMap(){
    var cct = {lat: 53.346, lng: -6.2588};
    var maracay = {lat: 10.2442, lng: -67.6066};

    var map = new 
        google.maps.Map(document.getElementById('map'),
            {
                zoom: 4,
                center: cct
            }
        );
    
    var marker = new google.maps.Marker({
        position: cct,
        map: map
    });

    var marker2 = new google.maps.Marker({
        position: maracay,
        map: map
    });
}



Display your current position on the map

Use the reading of the GPS sensor (Using the Geolocation plugin) to pin point the location of the device on a Google Map.

To do so, we can create another an updateMap that will be very similar to the initMap but it will require the latitude and longitude as arguments. We can then call this function from the geoCallback function and pass it the latitude and longitud:


index.js:

//* Create a new function called getLocation() to wrap up the getCurrentPosition function provided by the plugin:
function getLocation(){
    navigator.geolocation.getCurrentPosition(geoCallback, onError);
}

//* Create the geoCallback function:
function geoCallback(position){
    console.log(position);

    var latitude = position.coords.latitude;
    var longitude = position.coords.longitude;

    var lat_lon = "Latitud: "+latitude+"  ;  Longitude: "+longitude;
    document.getElementById("geoPlaceholder").innerHTML = lat_lon;


    // Create the map with the current location
    updateMap(latitude, longitude);
}

//* Create the onError function:
function onError(message){
    console.log(message);
}


function updateMap(latitud, longitud){

    var location = {lat: latitud, lng: longitud};

    var map = new 
        google.maps.Map(document.getElementById('map'),
            {
                zoom: 4,
                center: location
            }
        );
    
    var marker = new google.maps.Marker({
        position: location,
        map: map
    });
}



Opencagedata

https://opencagedata.com/dashboard

This API will take your latitude and longitude and return some data regarding your place, such as name of the city/country, currency, road name, post code, among others.

They offer a free plan that allows 2500 requests per day.


Ex:

https://api.opencagedata.com/geocode/v1/json?q=LAT%LONG&key=YOUR_KEY&language=en&pretty=1
https://api.opencagedata.com/geocode/v1/json?q=51.952659%2C%207.632473&key=4e72525ad45c499691653be8cbbe077e&language=en&pretty=1



NewsAPI

https://newsapi.org

Registration complete

Your API key is: 669e94373b734a7f9e056b56d5bbca8f

For help getting started please look at our getting started guide.

We post API status updates and other news on our Twitter feed, so please follow us there if that's important to you:


This API just return a JSON file. There are some examples in the home page at https://newsapi.org. For example, enter this in the web browser:

  • All articles about Bitcoin from the last month, sorted by recent first
https://newsapi.org/v2/everything?q=bitcoin&from=2019-10-03&sortBy=publishedAt&apiKey=669e94373b734a7f9e056b56d5bbca8f


  • Top business headlines in the US right now:
https://newsapi.org/v2/top-headlines?country=us&category=business&apiKey=669e94373b734a7f9e056b56d5bbca8f


  • All articles mentioning Apple from yesterday, sorted by popular publishers first:
https://newsapi.org/v2/everything?q=apple&from=2019-11-02&to=2019-10-20&sortBy=popularity&apiKey=669e94373b734a7f9e056b56d5bbca8f


  • Top headlines from The Verge right now:
https://newsapi.org/v2/top-headlines?sources=the-verge&apiKey=669e94373b734a7f9e056b56d5bbca8f


  • All articles published by the Wall Street Journal in the last 6 months, sorted by recent first:
https://newsapi.org/v2/everything?domains=wsj.com&apiKey=669e94373b734a7f9e056b56d5bbca8f


Here you can find some JavaScript examples: https://newsapi.org/docs/get-started

One of the examples in the above source is:

  • I want to search for news articles that mention a specific topic or keyword:
var url = 'https://newsapi.org/v2/everything?' +
          'q=Apple&' +
          'from=2019-10-21&' +
          'sortBy=popularity&' +
          'apiKey=669e94373b734a7f9e056b56d5bbca8f';

var req = new Request(url);

fetch(req)
    .then(function(response) {
        console.log(response.json());
    })



OpenWeatherMap API

https://openweathermap.org

Your API Key is: 315d8c67976f00f0176e17bbf1adf7c9


The OpenWeatherMap API documentation structure is based on our product list. You can choose a product you are interested in and find detailed technical instructions clicking on the button API doc opposite the product name: https://openweathermap.org/current


There are many products provided for this API:

  • Current weather data
  • Climate forecast for 30 days
  • Hourly forecast
  • ... etc



Current weather data

https://openweathermap.org/current

This product allows you to access current weather data for any location on Earth including over 200,000 cities.


By city name:

The general Syntax (for all the products of the API) for using the API key in API call is:


In the case of the Current weather data product, the API call would be:

  • Call by city name:


  • Call by city ID:


Example:

index.html
<input id="weatherInput" type="text" value="Enter a city">
<button id="weatherTrigger" onclick="openWeatherMapAPI()">Submit</button>
index.js
function openWeatherMapAPI(){

    var weatherInput = document.getElementById("weatherInput").value;
    console.log(weatherInput);

    var http = new XMLHttpRequest();
    const url = 'http://api.openweathermap.org/data/2.5/weather?q='+weatherInput+'&APPID=315d8c67976f00f0176e17bbf1adf7c9';
    http.open("GET", url);
    http.send();

    http.onreadystatechange = (e) => {
        var response = http.responseText;
        var responseJSON = JSON.parse(response);
        console.log(responseJSON);
    }
}



Currency Conversion API

https://currencylayer.com/


Take a look at an example here: https://currencylayer.com/dashboard


By default, the API returns the conversion rate between USD to many other currencies:

http://www.apilayer.net/api/live?access_key=cb51ac5d62bd1e6713b4b6c6e015d6b6


We can also customize the request by doing something like this:

http://apilayer.net/api/live?access_key=cb51ac5d62bd1e6713b4b6c6e015d6b6&currencies=EUR,GBP,CAD,PLN&source=USD&format=1
http://apilayer.net/api/live
    ? access_key = cb51ac5d62bd1e6713b4b6c6e015d6b6
    & currencies = EUR,GBP,CAD,PLN
    & source = USD
    & format = 1


The above request will return this JSON file:

success:    true
terms:      "https://currencylayer.com/terms"
privacy:    "https://currencylayer.com/privacy"
timestamp:  1572797345
source:     "USD"
quotes:
     USDEUR  0.895456
     USDGBP  0.773037
     USDCAD  1.31595
     USDPLN  3.80865


Example:

index.html
<!-- Title of the App -->
<div style="font-weight: bold;  font-size: 15px;" id ="label">Euro (€) - American Dollar ($) Convertor</div><br />

<!-- Label asking for the amount to be converted -->
<div id ="label">Enter the amount you want to convert ($ or €):</div>
<input type="number" id ="amount"> <br />

<!-- Button to trigger the function that will perform the conversion (From $ to €) -->
<button id="buttonToEuro" onclick="convertCurrency(this.id)"> Convert to € </button> <br />

<!-- Button to trigger the function that will perform the conversion (From € to $) -->
<button id="buttonToDollar" onclick="convertCurrency(this.id)"> Convert to $ </button>

<!-- Placeholder in which the result will be displayed -->
<div id ="currencyPlaceholder"> Display result... </div>


index.js
// #############################################################
// Currency Conversion API
// #############################################################
function convertCurrency(clicked_id){

    // Getting the value (amount to convert) entered by the user:
    var amount = document.getElementById("amount").value;
    // Printing the amount in the console for debugging purposes
    // console.log(amount);

    console.log(clicked_id);
    // Printing the clicked_id in the console for debugging purposes
    // console.log(clicked_id);

    // *** Reading JSON from URL with XMLHttpRequest *** 
    // A new instance of XMLHttpRequest is created
    var http = new XMLHttpRequest();

    // Requesting the conversion rate from the external API https://currencylayer.com
    // By default, the API returns the conversion rate between USD and many other currencies:
    const url = 'http://www.apilayer.net/api/live?access_key=cb51ac5d62bd1e6713b4b6c6e015d6b6';
    // We can also customize the request by doing something like this:
    // const url = 'http://apilayer.net/api/live' +
    //             '?access_key=cb51ac5d62bd1e6713b4b6c6e015d6b6' +
    //             '&currencies=EUR,GBP,CAD,PLN' +
    //             '&source=USD' +
    //             '&format=1';

    // The open() method initializes a request
    http.open("GET", url);

    // The send() method sends the request; the request is asynchronous by default
    http.send();

    // Here the readystatechange event is fired so we can obtain the response:
    http.onreadystatechange = (e) => {
        var response = http.responseText;

        // Response as a JSON file:
        var responseJSON = JSON.parse(response);

        // Printing the responseJSON in the console for debugging purposes
        // console.log(responseJSON);

        // Updating the placehoder reserved for the result of the converted amount 
        // If the «buttonToEuro» is clicked, we convert the amount entered (that is supposed to be in $) to €uro.
        // To do so, we multiply the amount entered by the conversion rate:
        if (clicked_id == "buttonToEuro"){
            document.getElementById("currencyPlaceholder").innerHTML = amount*responseJSON.quotes.USDEUR;
        // If the «buttonToDollar» is clicked, we convert the amount entered to Dollars:
        } else {
            document.getElementById("currencyPlaceholder").innerHTML = amount/responseJSON.quotes.USDEUR;
        }
        
    }

}



Cordova with ReactJS

Because Cordova converts a Web App into an Native Mobile App, you can use a Framework or Library to build your Web App that will be converted by Cordova.


  • how to Integrating ReactJS into an Apache Cordova Project:
  • I thinks that none of the above post explain well how to do it. No pude hacerlo de esta forma. Sin embargo, no insistí por mucho tiempo en este método.



  • Reco (React+Cordova) unifies React.js and Cordova into one CLI which bundles both platforms together and provides the developer with the ability to generate Cordova hybrid cross-platform applications built in React.js.


  • There is also Reapp; which is also a way to build apps with React and JavaScript that can be built with Cordova.



Cordova React Template

https://www.npmjs.com/package/cordova-react



Reco

Reco (react.cordova)

https://www.npmjs.com/package/react.cordova


Reco (React+Cordova) unifies React.js and Cordova into one CLI which bundles both platforms together and provides the developer with the ability to generate Cordova hybrid cross-platform applications built in React.js.

La primera vez que probé Reco pude generar exitosamente un proyecto que integraba Cordoba y React; el cual fui capaz de serve en el web browser.

After installing and creating a Reco project, I was able to easily build the Mobile App (generate the .apk) by just running:

reco build android

I didn't get any error running the above command, which surprise me because when I was learning how to build the App using Cordova CLI I had to troubleshooting and install different packages to be able to successfully build the App. Everything have been documented in the corresponding section Cordova - PhoneGap#Building the Cordova App. Actually, I think that I didn't have any issues when running reco build android because I suppose this command works similar to cordova build android and all the troubleshooting and steps necessarily to successfully run this command had already been completed.


However, luego traté de general un proyecto similar y se generaron errores que, aunque no traté por mucho tiempo de resulverlos, no me permitieron generar correctamente un proyecto Cordova-React. Los errores se generaban al momento de crear el proyecto React.


Ahora, como veremos más adelante, Reco me permitió generar la estructura de un proyecto Cordova-React que luego fui capaz de integrar con un proyecto Ionic-React



Reapp

http://www.reapp.io/

An easier, faster way to build apps with React and JavaScript. Reapp is everything you need to build amazing apps with React: a collection of packages that work together, our UI kit, and a CLI that scaffolds your app and includes a server and build system.


Reapp tutorial

https://www.sitepoint.com/creating-mobile-application-reapp/

The app will help a user save different locations, making use of the Google Maps API. It will use Firebase as a back end to save data.



Example of an Cordova App created with ReactJS

https://medium.com/the-web-tub/creating-a-cordova-hybrid-app-with-react-redux-and-webpack-13fe24b6b272

https://github.com/argelius/react-onsenui-redux-weather

Este tutorial no usa Reco ni Reapp. Creo que la configuración del React project y el Cordova project se hizo manualmente.

This tutorial muestra como realizar una Cordova App using react. La App se puede descargar y funciona bien. Me parece un buen examen. Sin embargo, el tutorial no explica correctamente como se configuró la estructura del poyecto Cordova - React. No creo hayan utilizado el Reco.


To run it simply do:

npm install
npm start


After run it the first time, I only had a error that was solved doing:

npm install onsenui@2.0.4

as it was proposed in this tutorial: https://github.com/argelius/react-onsenui-redux-weather/issues/7



How to use a Cordova plugin in react JS page

https://stackoverflow.com/questions/50572956/how-to-use-a-cordova-plugin-in-react-js-page