Chapter 5.Apache Cordova Basics
The Ionic Framework is built upon two other technologies: Angular and Apache Cordova. In this chapter, we will explore what Apache Cordova is and how it interacts with Ionic.
Apache Cordova is an open source framework that enables mobile app developers to use their HTML, CSS, and JavaScript content to create a native application for a variety of mobile devices. Let’s look further at how this works.
Cordova takes your web application and renders it within a native web view. A web view is a native application component (like a button or a tab bar) that is used to display web content within a native application. You can think of a web view as a web browser without any of the standard user interface chrome, like a URL field or status bar (seeFigure 5-1). The web application running inside this container is just like any other web application that would run within a mobile browser—it can open additional HTML pages, execute JavaScript code, play media files, and communicate with remote servers. This type of mobile application is often called a hybrid application.
Figure 5-1.How Cordova applications are composited to create fully native applications
Typically, web-based applications are executed within a sandbox, meaning that they do not have direct access to various hardware and software features on the device. A good example of this is the contact database on your mobile device. This database of names, phone numbers, emails, and other bits of information is not accessible to a web app. Besides providing a basic framework to run a web app within a native application, Cordova also provides JavaScript APIs to allow access to a wide variety of device features, like the contacts database. These capabilities are exposed through the use of a collection of plugins. We will explore their use later in this book, but plugins provide a bridge between our web application and the device’s native features. There is a core set of plugins that is maintained by the Cordova project, as well as a large collection of third-party plugins that offer even more functionality (NFC communication, Force Touch, and Push Notifications, just to name a few)—seeTable 5-1.
Plugin | Function |
Battery status | Monitors the status of the device’s battery |
Camera | Captures a photo using the device’s camera |
Console | Provides an improved console log |
Contacts | Works with the device’s contact database |
Device | Gathers device-specific information |
Device motion (accelerometer) | Taps into the device’s motion sensor |
Device orientation (compass) | Obtains the direction the device is pointing to |
Dialogs | Visual device notifications |
File | Hooks into native file system through JavaScript |
File transfer | Allows your application to upload and download files |
Geolocation | Makes your application location aware |
Globalization | Enables representation of objects specific to a locale |
InAppBrowser | Launches URLs in another in-app browser instance |
Media | Records and plays back audio files |
Media capture | Captures media files using device’s media capture applications |
Network connection | Quickly checks the network state and cellular network information |
SplashScreen | Shows and hides the application’s splash screen |
StatusBar | An API for showing, hiding, and configuring status bar background |
Vibration | An API to vibrate the device |
Whitelist | Implements a whitelist policy for navigating the application WebView |
The History of Cordova (aka PhoneGap)
Developers are often confused by the difference between Apache Cordova and PhoneGap. In an attempt to clear up this confusion, we need to understand the origins of this project. In late 2008, several engineers from Nitobi attended an iPhone development camp at the Adobe offices in San Francisco. They explored the idea of using the native web view as a shell to run their web applications in a native environment. The experiment worked. Over the next few months, they expanded their efforts and were able to leverage this solution to create a framework. They named the project PhoneGap, since it allowed web developers the ability to bridge the gap between their web apps and the device’s native capabilities. The project continued to mature, and more plugins were created, enabling more functionality to be accessed on the phone. Other contributors joined the effort, expanding the number of mobile platforms it supported.
In 2011, Adobe bought Nitobi, and the PhoneGap framework was donated to the Apache Foundation. The project was eventually renamed Cordova (which is actually the street name of Nitobi’s office in Vancouver, Canada).
Apache Cordova versus Adobe PhoneGap
Since there is both Apache Cordova and Adobe PhoneGap, it is quite easy to confuse the projects. This naming issue can be a source of frustration when researching an issue during development and having to search using both Cordova and PhoneGap as keywords to find the solutions, or even reading the proper documentation, as the two projects are so intertwined.
A good way to understand the difference is to think about how Apple has its Safari browser, but it is based on the open source WebKit engine. The same is true here: Cordova is the open source version of the framework, while PhoneGap is the Adobe-branded version. But in the end, there is little difference between the two efforts. There are some slight differences in the command-line interfaces, but the functionality is the same. The only thing you cannot do is mix the two projects in the same application. While not as dangerous as when the Ghostbusters crossed their streams, using both Cordova and PhoneGap in the same project will produce nothing but trouble.
PHONEGAP OR CORDOVA?
We tend to use PhoneGap as our primary search term since that was its original name when researching issues.
The main difference between the projects is that Adobe has some paid services under the PhoneGap brand, most notably thePhoneGap Buildservice. This is a hosted service that enables you to have your application compiled into native binaries remotely, eliminating the need to install each mobile platform’s SDKs locally. The PhoneGap CLI has the ability utilize this service, while the Cordova CLI does not.
The other difference is the PhoneGap CLI can be used in tandem with thePhoneGap developer app. This free mobile app allows for your app to run on-device without the need to first compile it. This provides a very easy method to test and debug your application on-device. Don’t worry, there is anIonic equivalentfor us to leverage, and we will be using it during our development cycle.
In this book, we will be using the Cordova command-line tool when we are not using the Ionic command-line tool. This is in part due to the fact the Ionic CLI is based on the Cordova CLI, not the PhoneGap CLI.
A Deep Dive into Cordova
In the past, configuring a Cordova project was a difficult task. It meant first creating a native application project in each platform’s IDE, then modifying it to support the interfaces for Cordova. With the release of the command-line tool, this process became easier. The CLI scaffolds a basic project and configures it to work with any supported mobile platform you can use.The Cordova CLI also allows us to have easy integration and management of the plugins for our project. Finally, the CLI enables us to quickly compile our app to run in a simulator or on an actual device. We will be exploring these commands further as we work through our sample applications.
Configuring Your Cordova App
Each Cordova application is defined by its_config.xml_file. This global configuration file controls many of the aspects of the application, from app icons, plugins, and range of platform-specific settings. It is based on theW3C’s Packaged Web Apps (Widgets) specification. The Ionic CLI will generate a starter_config.xml_file during its scaffolding process.
As you develop your Ionic application, you will need to update this file with new elements. Some common examples of this are adjusting the app name, the app ID string, or adding a platform-specific setting likeandroid-minSdkVersion
.
A deeper exploration of the_config.xml_can be found inAppendix A.
Device Access (aka Plugins)
Some of the real power of Cordova comes from its extensive plugin library. At the time of this writing, there were over2,570 plugins. But what is a Cordova plugin? Here is how the Cordova website defines them:
A plugin is a bit of add-on code that provides JavaScript interface to native components. They allow your app to use native device capabilities beyond what is available to pure web apps.
As mentioned earlier, there are two sets of plugins: core and third-party. Time for another brief history lesson. Up to version 3.0 of PhoneGap (pre-Cordova), the code base contained both the code to use the WebView and its communication to the native app, along with some of the “key” device plugins. Starting with version 3.0, all the plugins were separated out as individual elements. That change means that each plugin can be updated as needed, without having to update the entire code base. These initial plugins are known as the “core” plugins.
But what about the other 2,540 or so plugins—what do they provide? An incredibly wide range of things: Bluetooth connectivity, push notifications, TouchID, and 3D Touch, just to name a few.
Interface Components: The Missing Piece
While Cordova provides a lot of functionality to the developer in terms of being able to leverage code across multiple platforms, extend beyond the web, and use native device features, it is missing one critical component: user interface elements. Beyond just the basic controls that HTML provides by default, Cordova does not offer any components like those found in a native SDK. If you want to have a tab bar component, you are either going to have to create the HTML structure, write the needed CSS, and develop the JavaScript to manage the views, or use a third-party framework, like Ionic.
This lack of a UI layer has often been one of the difficulties in working with Cordova. With the release of the Ionic Framework, developers now have a first-rate interface toolkit with which they can author their mobile applications. There are other solutions available for a Cordova application, but this book is focused on Ionic. If you would like to look at some other options, you might look at OnsenUI, Framework7, or ReactJS as an option. For me, I have been very pleased with what I have been able to build with the Ionic Framework and its services.
Why Not Cordova?
Although Cordova is an incredibly powerful solution for building mobile applications, it is not always the right choice. Understanding the advantages and disadvantages of the framework is critical in how well your application will perform. Our Cordova application is several layers away from the actual native layer. So, great care must be taken to develop a performant Cordova application. This was very true during the early days of PhoneGap, when devices were relatively low powered. Current mobile devices have much more computing power that can be used.
With that said, you are not going to develop the nextAngry Birds_or_Temple Run_using Cordova. But you might be able to build the next_Quiz Up,Untappd, orTrivia Crack.
Understanding Web Standards
Another thing to consider is what the WebView is actually capable of. Although most mobile WebViews are fairly current with recognized web standards, it is always worthwhile to understand there might be issues or quirks.If you have been doing any modern web development, there is a good chance you have usedhttp://caniuse.com.
This is an excellent resource to check if a particular HTML5 feature is available, or if a CSS property is supported. For example, if we wanted to use scalable vector graphics (SVGs) in our application to assist in dealing with a range of screen sizes and densities, we can go to_http://caniuse.com_and see when each mobile platform began supporting it (Figure 5-2).
In this case, we can see that while iOS has had support for several versions, the Android platform only recently enabled support for this format.
It is worth noting exactly where the WebView that Cordova uses comes from. When you compile your application, Cordova does not actually include a WebView into the application. Instead, it will use the WebView that is included on the device as part of its OS. That means current iOS devices get a version of WebKit, while certain Android devices will be using Chromium, and others might still be using WebKit.
Figure 5-2.SVG support across various browsers
Although recently active development was halted, theCrosswalk Projectis still a worthwhile solution if you need to release your application for older Android devices. This plugin replaces the default WebView in your Cordova project with the latest version of Google Chromium, thus giving you the latest browser support. Although using this solution will increase the size of your application, it can help in normalizing the web features that you can use. If your application will be used by older Android devices, using Crosswalk can great resolve some of the browser issues that exist.
Summary
Now you should have a better understanding of how Apache Cordova works and how it enables you to use your web technology skills to create mobile applications. In this chapter, we looked at how Cordova bridges between the native layer and the web technology layer. It’s plugin architecture was introduced, which will allow us to access native device features in our hybrid applications. We touched on whether this solution was the right choice for your development needs. Finally, we covered why there is a need for a framework like Ionic.
Chapter 6.Understanding Ionic
Let’s now take a deeper look at what makes up the foundation of an Ionic page. Each Ionic page is formed from three base files: an HTML file which defines the components that are displayed; a Sass file which defines any custom visual styling for those components; and a TypeScript file which will provide the custom functions for those components. Since Ionic is built upon web technologies, we can use many of the same solutions that we might use in developing a traditional web application or web page (Figure 6-1).
Figure 6-1.Basic Ionic page structure
HTML Structure
Unlike in a traditional HTML file, you do not need to include the<head>
tag and any elements like importing CSS files or other code libraries. You also do not include the<body>
tag nor even the<!DOCTYPE html>
or<html lang="en" dir="ltr">
tags. The contents of this HTML file are rendered within our application container, so we do not need them. We just define the actual components that will be shown to the user. These components are a mixture of traditional HTML tags, as well as custom tags that are used to define the Ionic components. Here is a sample of an Ionic page’s markup.
<
ion-header
>
<
ion-navbar
>
<
ion-title
>
Ionic Blank
<
/ion-title
>
<
/ion-navbar
>
<
/ion-header
>
<
ion-content padding
>
The world is your oyster.
<
p
>
If you get lost, the
<
a href="http://ionicframework.com/docs/v2"
>
↵
docs
<
/a
>
will be your guide.
<
/p
>
<
/ion-content
>
The rendered Ionic page is shown inFigure 6-2.
You can see the markup is a blend of standard HTML (<p>
and<a>
) and Ionic tags (<ion-header>
,<ion-content>
, etc).
Figure 6-2.The rendered page
Ionic Components
One of Angular’s features is the ability to extend the vocabulary of HTML to include custom tags. The Ionic Framework leverages this capability and has created an entire set of mobile components. These include components like<ion-card>
,<ion-item-sliding>
, and<ion-segment-button>
. For a complete summary of the Ionic component library, seeAppendix C, as well as theIonic documentation. All of the Ionic components have the prefixion-
, so they are easy to spot in the markup.
AUTOCOMPLETING IONIC TAGS
Most code editors offer some form of autocomplete or code-hinting that can be extended. There is usually a downloadable plug-in for your editor that enables code hinting for the Ionic Framework.
Behind the scenes, each of the components is decomposed at runtime into basic HTML tags with their custom CSS styling and functionality.
Just like standard HTML tags, Ionic components also accept various attributes to define their settings, such as setting their ID value or defining additional CSS classes. But Ionic components are also extended through additional attributes like:
<
ion-item-options
side="left"
>
or using Angular directives:
<
button
ion-button
color="dark"
>
As we build our sample applications, you will become more familiar with the Ionic component library.
Understanding the SCSS File
The visual definition of an Ionic application is defined by CSS. However, this CSS is actually generated bySass, or Syntactically Awesome Style Sheets. If you have never worked with Sass, it provides several advantages over writing CSS directly. These include the ability to declare variables like$company-brand: #ff11dd
. You can reference this variable instead of directly assigning the color. Now if we had to change our color, we only have to do it in one location and not across multiple files.
CSS VARIABLE NAMING
It is often tempting to give the variable a name like$company-red
, but consider what happens if the branding changes and instead of red, the color is actually green?
All of Ionic’s components are styled using Sass variables. For example, we can change the$list-background-color
by adding our value in the_app.variables.scss_file. The team has done an incredible job in ensuring that each Ionic component is easy to style. Refer to the Ionic documentation for a complete list of all the configurable Sass variables.
Sass also supports an improved syntax for writing nested CSS. Here is an example of this:
nav {
ul {
margin: 0;
padding: 0;
list-style: none;
}
li { display: inline-block; }
a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
}
When transformed, it becomes:
nav ul {
margin: 0;
padding: 0;
list-style: none;
}
nav li {
display: inline-block;
}
nav a {
display: block;
padding: 6px 12px;
text-decoration: none;
}
This method of writing CSS shorthand can be a real timesaver.
Typically, the screen’s.scss_file is where you will define any page-specific CSS—for example, if you need to have a slightly different button style for a login screen. By defining it in the associated.scss_file, you keep the associated elements package together in a more logical fashion. For any application-wide theming, that styling should be defined in the_app.core.scss_files.
We will explore theming in greater detail when we are building our sample applications.
Understanding TypeScript
The last element needs to create an Ionic screen is the associated TypeScript (.ts) file. This where all the Angular/TypeScript code to control the interactions of this page will be written.
The file will define any code modules we need to import for our screen to function. Typically, these would be components that we might need to programmatically interact with (like navigating to a new screen) or Angular modules that offer needed functions (like making an HTTP request). It will also define the base component that is actually our screen. As we need to add functions to respond to user input, that code will also be added into this file. Here is what a basic Ionic_.ts_file looks like:
import { Component } from '@angular/core';
import { NavController } from 'ionic-angular';
@Component({
selector: 'page-home',
templateUrl: 'home.html'
})
export class HomePage {
constructor(public navCtrl: NavController) {
}
}
This TypeScript code just defines theHomePage
component and links it the template.
We will be working a lot of TypeScript code throughout our sample applications, so we will not go any further in exploring this element.
Summary
You should have a better understanding of the three key elements that make up a single Ionic screen: the HTML file, the Sass file, and the TypeScript file. Let’s move on to building our first actual Ionic application.