Chapter 12.Exploring the Ionic Services

Ionic is more than just a framework to build mobile applications; it is also a collection of cloud-based services. These services include the ability to compile your application remotely, update deployed applications without resubmitting, and generating the user interface through a visual builder. The focus of the Ionic Services is to directly support the actual development of your mobile application. Unlike the Ionic Framework, which is open source, these services require a monthly fee. But don’t worry: most of them have a development version, so you can explore them at no charge—with some usage limitations.

NOTE

Initially, the Ionic Services also contained some additional services like user authentication, analytics, and database support. These services have been or being shut down.

NOTE

Ionic has announced they are deprecating the existing Ionic Cloud and will migrate to a new system known as Ionic Pro. The scheduled date for this is January 31, 2018.

Setting Up Ionic Services

Before we can begin using any of the Ionic Services, we will need to create afree account.

Next, we need to install the Ionic Cloud client in the app. Make sure your active directory is the at the root level of your application. Then run this command to install the client:

$ npm install @ionic/cloud-angular --save

Generating Your Ionic App ID

Before we can configure our app to use the Ionic Cloud, we need to have an Ionic App ID. This a different ID from the app ID found within the_config.xml_file. Still, within your project directory, run this command:

$ ionic link

This command will now prompt you to either select from an existing application or create a new app. If you select, create a new app, your browser will open and you can generate a new app in the Dashboard.

Figure 12-1.The Ionic Cloud Dashboard

Once you have completed that step, return to the CLI and runionic linkagain, this time selecting the app name you just created. An automatically generated app ID will be saved in your_ionic.config.json_file. You may need to provide your Ionic.io username and password to proceed.

Once the CLI has updated the_ionic.config.json_file, go ahead and open this file and copy the generated app ID; we are going to need this value in the next step.

Configuring Your Application

With our app now registered with the Ionic Services, we need to update our app’s bootstrapping process. Open your_app.module.ts_file in your editor.

We first need to import the Ionic Cloud module:

import { CloudSettings, CloudModule } from '@ionic/cloud-angular';

Next, define a constant that will define our Ionic Cloud setting. Replace theAPP_IDin the code sample with the value you found in theionic.config.json:

const cloudSettings: CloudSettings = {
  'core': {
    'app_id': 'APP_ID'
  }
};

Within the@NgModule, we need to include our CloudModule in the imports array:

@NgModule({
  declarations: [ ... ],
  imports: [
    IonicModule.forRoot(MyApp),
    CloudModule.forRoot(cloudSettings)
  ],
  bootstrap: [IonicApp],
  entryComponents: [ ... ],
  providers: [ ... ]
})

Our application is now ready to utilize the Ionic Services.

Ionic Deploy

One service offered in the Ionic Services is Ionic Deploy. Since the core of our application is not really compiled into the native app’s codebase, it is possible to swap out our HTML, JS, and CSS without needing to recompile the application. If you have used either the Ionic View app or the PhoneGap Developer App, this is core technology that powers both of those applications.

Here’s what you can do by enabling live deployment of your application:

  • Bypass app store approvals
  • Update your app on demand
  • Push new features and bug fixes to your users effortlessly
  • Perform A/B user testing

When working with Ionic Deploy, you will need to know somespecific terminology:

Snapshot

The bundled version of your app’s code. This is the package that will be sent to the user’s device.

Live Deployment

This refers to when the active snapshot is download and running on a device.

Channel

Snapshots are released to specific deploy channels. Channels allow you to deploy different snapshots of your app to different devices.

Binary Update

When you need to update the native portion of your application, usually if a plug-in or a Cordova update is needed.

Setting Up Ionic Deploy

To demonstrate this service, we are going to create a new Ionic project based on the blank template. From the command line, run the following:

$ ionic start IonicDeploy blank

You will need to install the initial Ionic Cloud component and initialize your app to use the Ionic Cloud.

In addition, you will need to install the Ionic Deploy plug-in. This plug-in will handle the actual updating of your app on both Android and iOS devices. With your application’s project directory active in your terminal, run this command:

$ ionic cordova plugin add ionic-plugin-deploy --save

With the plug-in installed, we can create the system to check for new deployments, download and extract them, and then enable them.

Testing Ionic Deploy

The Ionic Deploy functionality can only run in an emulator or on an actual device. You will not be able to service within a browser.

ENABLING IONIC DEPLOY

Open the_home.ts_file and first add theDeploymodule to the imports:

import { Deploy } from '@ionic/cloud-angular';

Then include it within theconstructor:

constructor(public navCtrl: NavController, public deploy:Deploy) {

}

Before we continue, we need to explore the concept of deploy channels. By setting different channels, you can manage various snapshots of your app to different devices. By default, there are three channels available: production, staging, and dev. You can create more channels if you need to (Figure 12-2).

Figure 12-2.Channel configuration dialog

Within our constructor, let’s set our deploy channel to"dev":

this.deploy.channel = 'dev';

This will tell Ionic Deploy to only refer to that channel when looking for any snapshots. If you do not define a channel, then it will default to production.

The app will need to conduct the following steps to implement live deployments:

  1. Check if a new snapshot has been deployed.
  2. Apply the snapshot.
  3. Reload the app.

CHECKING FOR A NEW SNAPSHOT

To see if a new snapshot is available from the Ionic Cloud, we simply calldeploy.check(). Since this is a network call, we will wrap it within a Promise:

this.deploy.check().then((snapshotAvailable: boolean) =
>
 {
  // When snapshotAvailable is true, you can apply the snapshot
  if (snapshotAvailable) {
    alert('Update is Available');
  } else {
    alert("No Updates Available");
  }
}).catch ((ex) =
>
 {
  console.error('Deploy Check Error', ex);
});

Whencheck()is called, it returns a boolean if there is a snapshot available to be downloaded. Note that we will use alerts to monitor the flow through the process.

If there is a snapshot available, we can begin the download by callingdownload(). This call should also be wrapped within a Promise:

this.deploy.download().then(() =
>
 {
  alert('Downloading new snapshot');
}).catch((ex) =
>
 {
  console.error('Deploy Download Error', ex);
});

Once the snapshot has completed its download to the device, we can have the snapshot extracted:

this.deploy.extract().then(() =
>
 {
   alert('Extracting snapshot');
}).catch((ex) =
>
 {
  console.error('Deploy Extract Error', ex);
});

After theextract()method’s Promise resolves, you can then trigger an immediate app restart using theload()method. Otherwise, the new snapshot will be run the next time the app is run. For this sample, we will trigger the automatic restart, although we would highly recommend that you give the user the opportunity to control the restart:

this.deploy.extract().then(() =
>
 {
   alert('Extracting snapshot');
   this.deploy.load();
}).catch((ex) =
>
 {
  console.error('Deploy Extract Error', ex);
});

Here is the complete code block:

this.deploy.check().then((snapshotAvailable: boolean) =
>
 {
  // When snapshotAvailable is true, you can apply the snapshot
  if (snapshotAvailable) {
    alert('Update is Available');
    this.deploy.download().then(() =
>
 {
      alert('Downloading new snapshot');
      this.deploy.extract().then(() =
>
 {
         alert('Extracting snapshot');
         this.deploy.load();
      }).catch((ex) =
>
 {
        console.error('Deploy Extract Error', ex);
      });
      // return this.deploy.extract();
    }).catch((ex) =
>
 {
      console.error('Deploy Download Error', ex);
    });
  } else {
    alert("No Updates Available");
  }
}).catch ((ex) =
>
 {
  console.error('Deploy Check Error', ex);
});

With our live deployment code in place, save this file and then let’s create our first snapshot.

CREATING A SNAPSHOT

When creating a snapshot, the contents of the_www_directory are uploaded to the Ionic servers. This means we need to generate a build into this directory before we call$ ionic upload. The easiest method is to simply run$ ionic serve. Don’t be concerned that our deploy checking code will not function in our browser; we just need a current build.

To create a snapshot, we need to upload our app’s code to the Ionic Cloud via the CLI. The base command is:

$ ionic upload

However, you can additionally include a short description of the snapshot, as well as the channel you want the snapshot deployed to. Run this command to create our first snapshot:

$ ionic upload --note "Initial Deploy" --deploy dev

Now if you run your application in an emulator, you might be surprised to see that our app will actually go through the update process. Since no snapshot has been downloaded, Ionic Deploy will check the local registry, and inform the system that there is an update available. Go ahead and let the process proceed. Once the initial snapshot is downloaded, extracted, and applied, our app will reboot. Now when our code checks the snapshot version, it will match and our update logic will exit. Let’s make a small change to our app so we can see a real update in action.

Openhome.html_and change the title of the page to Ionic Deploy Test. Since the first line of the text is from_The Merry Wives of Windsor, let’s swap it out as well.

Save our file and make sure you run your application once with$ ionic serve. Then create a new snapshot by running:

$ ionic upload --note "Second Deploy" --deploy dev

Now if you emulate or build your app again, it will create a new version, and you will not see the live deployment functioning. Simply run the app in either your emulator or on an actual device. Our update alerts will appear again, and then we will see our new content (Figure 12-3).

Figure 12-3.Our app updated via Ionic Deploy

If we bring up our Ionic Services dashboard, we can see our snapshots (Figure 12-4).

Figure 12-4.Ionic Deploy dashboard

From this page, we can manage our deployments in our various channels. If we need to channel an active snapshot, we can do this as well. At the time of writing, there is no method to delete a snapshot from the Ionic Cloud. Proper descriptions will be critical in identifying your snapshots. You may also want to test out your application’s live deployment logic in a sample app, not your production app.

SETTING SNAPSHOT METADATA

You can also include custom metadata with your snapshot. This metadata is added through the dashboard as key/value pairs, For example, you could include release notes as a metadata item.

To retrieve this information from the Ionic Cloud, use thegetMetadata()method:

this.deploy.getMetadata().then((metadata) =
>
 {
  // use metadata
});

USING BINARY VERSIONING

Over time your application may have different binaries deployed. There may be changes in the versions of Cordova plug-ins, or even Cordova itself in your app. This may cause an incompatibility between a new snapshot and the older released application. To prevent this, you can use Ionic Cloud’s binary versioning feature. Binary versioning lets you halt live deployments on devices that would otherwise break the app. Binary versioning requires that you use a semantic version for your build version (which is set in your_config.xml_file).

SEMANTIC VERSIONING SCHEME

The semantic versioning format comprises three parts: major.minor.patch. When we compare versions, we adhere to version precedence. Example: 1.0.0→2.0.0→2.1.0→2.1.1.

There are three mechanisms you can use for both iOS and Android:

Minimum

Perform the deploy if the installed version is equal or higher.

Maximum

Perform the deploy if the installed version is equal or lower.

Equivalent

If the installed version is equivalent, do not perform the deploy. Remember to set this value when you publish to the app stores to prevent unnecessary live deployments.

With a little planning, you can introduce a powerful and rapid live deployment solution for your application.

Security Profiles

When using the Ionic Packaging service, the Ionic Cloud will need various signing certificates and keys in order to function. Security Profiles is a service that allows you to securely store these credentials and use them with those other services. So before we explore the Ionic Package service, let’s create our profile.

The following are the certificates and keys you will need based on the service and the platform:

Cloud Builds

  • Android: Keystore

  • iOS: Certificate & Provisioning Profile (dev/prod)

Push Notifications

  • Android: FCM Project & API Key

  • iOS: Certificate & Provisioning Profile & Push Certificate (dev/prod)

NOTE

You will need both a signing certificate and push notification certificate from Apple for each release mode (development or production).

Security profiles do not allow you to pick which certificate to use, so you will need to create two profiles: one for your development phase, and one for production.

Creating a Profile

Sign in to the Ionic.io website and select the app you want to create your profile(s) for. Since signing certificates and keys are directly tied to a particular app ID, so are security profiles. With an app selected, navigate to the Settings page and select Certificates, as shown inFigure 12-5.

Figure 12-5.Security Profile & Credentials dashboard

Click the New Security Profile button to bring up the New Security Profile dialog. Give your profile a name. The Ionic Cloud will generate a tag based on the profile name. This tag needs to be something command-line safe, meaning spaces will be replaced with underscores, and everything will be converted to lowercase. Referencing a security profile is done via its tag, not its profile name. Note that you can’t change this name at a later time. So feel free to provide a slightly more descriptive name. A single security profile can support both iOS and Android information (Figure 12-6).

Figure 12-6.New Security Profile dialog

iOS Setup

You will need to generate your App Development/App Store Certificate and your provisioning profile and uploaded them to your security profile. These files are generated through the Apple Developer Center website and either the Keychain Access tool (on macOS) or OpenSLL (on Windows). Rather than recreate these steps,follow the instructionsto generate the.p12_and.mobileprovision_files.

If you attempt to create an iOS App Development certificate and find that option disabled, it is because each team can have only one active distribution certificate. Locate the existing certificate and export it and continue the process as outlined.

With these files downloaded, we can now upload them to our security profile.

Supporting iOS Push Notifications

In order to use push notification, an additional certificate is required, as well as some additional settings. Just like you need to create two signing certificates for development and production, the same is true for push notifications.

Again,follow the instructions.

The main differences are you will need to define an explicit app ID instead of using a wildcard app ID, and you will need to make sure you enable push notifications in the options.

XCODE 8 AND HIGHER

If you’re using the latest version of Xcode, you will likely need to activate the push notifications capability before your app is able to receive notifications.

We will explore push notifications later in this chapter.

Android Setup

Android does not use a web portal to generate your signing key. Instead, it relies on thekeytoolcommand included in the Java JDK:

$ keytool -genkey -v -keystore MY-RELEASE-KEY.keystore -alias MY_ALIAS_NAME 
-keyalg RSA -keysize 2048 -validity 10000

ReplaceMY-RELEASE-KEY_andMY_ALIAS_NAME_to be relevant to your app. The tool will ask you to enter a keystore password and a key password. You will need to remember the alias name that you supplied when generating this keystore.

Then, simply upload the_.keystore_file to your security profile (Figure 12-7).

Figure 12-7.Android security profile dialog

Android Push Notifications

Like in iOS, some additional items are required in order to use push notifications.Google recently rebranded its cloud messaging service from Google Cloud Messaging (GCM) to Firebase Cloud Messaging (FCM).

To obtain your Google FCM server key, you will need to first create a new project on yourFirebase console. Then enter a name for your project and select the region for your project. Once your project is generated, display the project settings by clicking the gear icon next to your project’s name. Then select the Cloud Messaging tab. This screen will have your server key, which the Ionic security profile needs. Return back to your app in the Ionic dashboard, and select the profile you wish to attach this server key to (Figure 12-8).

Figure 12-8.Firebase Cloud Messaging console

We will explore push notifications later in this chapter.

With our security profiles set up, we can now use them with the Ionic Package service.

Ionic Package

Ionic Package allows you to build native binaries of your application without the need for installing local SDKs. This can be very useful for Windows developers who want to build for iOS. This service is very similar to PhoneGap Build from Adobe.

This process is done via the Ionic CLI, with a similar syntax to theionic buildcommand. As a reminder, you will need a security profile attached this app. You can verify this by going to your app’s profile on ionic.io.

NOTE

A security profile is not needed for Android development builds.

The base package command is:

$ ionic package build PLATFORM_TAG --profile PROFILE_TAG

ThePLATFORM_TAGcan be eitherandroidorios. ThePROFILE_TAGis the generated Security Profile tag found in Settings→Certificates in the Dashboard. Here is a sample of the output to the terminal:

Uploading your project to Ionic...
Submitting your app to Ionic Package...
Your app has been successfully submitted to Ionic Package!
Build ID: 1
We are now packaging your app.

Your code is then uploaded to Ionic.io and queued for building. Your app will be automatically assigned an ID; after a few minutes, a build should be available to download or share.

Preparing a Release Build

Ionic Package service can build development and release-ready builds. To build your app for production, include--releaseflag (you must have a production security profile with the corresponding Apple certificates for a release build):

$ ionic package build PLATFORM_TAG --profile PROFILE_TAG --release

Getting Build Information

Since your build request is now queued and it does take some time to perform, you can check the status of your builds by listing them:

$ ionic package list

This can be useful if you integrate this process into a generated build process. Here is a sample output:

  id │ status   │ platform │ mode  
─────┼──────────┼──────────┼──────
  1  │ BUILDING │ android  │ debug 

Showing 1 of your latest builds.

Getting Your Build Results

Once your build is complete, you can get its status by using this command:

$ ionic package info BUILD_ID

Here is what a successful build message will look like:

  id        │ 1                       
  status    │ SUCCESS                 
  platform  │ android                 
  mode      │ debug                   
  started   │ Nov 19th, 2016 14:43:08 
  completed │ Nov 19th, 2016 14:43:29

Downloading Your Build

Once your app has been successfully built, download the.ipa_or.apk_. These files will download to the app’s project folder:

$ ionic package download BUILD_ID

Downloading... [=============================]  100%  0.0s
Wrote: /Users/chrisgriffith/Desktop/Ionic Book Apps/
       Ionic2Package/Ionic2Package.apk
Done!

You can now install your app on any authorized device.

Updating Your Cordova Plug-ins

To ensure thatIonic Package’sbuild servers know which Cordova plug-ins your app needs, you should reinstall them into the project with the--saveflag added:

$ ionic cordova plugin add PLUGIN_NAME --save

To get a listing of the plug-ins used in your application, run:

$ ionic cordova plugin ls

Ionic View

Ionic View makes it easy to share your app with clients and testers without using TestFlight Beta Testing or Beta Testing through Google Play. Just upload your app and share it. The free mobile app is available for iOS and Android. This application will act as a native shell for your application to run within. The advantage of this option is that you do not need to compile your application before running it on an actual device.

Ionic View leverages the capabilities of Ionic Deploy to make this possible. Since it hosts your application within another shell, only a subset of the Cordova plug-ins are available to be used.

Supported Plug-ins

Here is the current list of plug-ins that Ionic View supports:

  • ActionSheet (2.2.2)

  • BarcodeScanner (5.0.0)

  • BLE (1.1.1)

  • Bluetooth Serial (0.4.5)

  • Calendar (4.5.0)

  • Camera (2.2.0)

  • Capture (1.3.0)

  • Contacts (2.1.0)

  • DatePicker (0.9.3)

  • DBMeter (1.0.3)

  • Device (1.1.2)

  • Device Motion (1.2.1)

  • Device Orientation (1.0.3)

  • Dialogs (1.2.1)

  • Email Composer (0.8.3)

  • Geolocation (2.2.0)

  • Globalization (1.0.3)

  • ImagePicker (1.1.1)

  • Keyboard (2.2.0)

  • Media (2.3.0)

  • Network Information (1.2.1)

  • SocialSharing (5.1.1)

  • SQLite (1.4.2)

  • StatusBar (2.1.3)

  • Toast (2.5.2)

  • Touch ID (3.2.0)

  • Vibration (2.1.1)

Check theIonic websitefor the latest information about which plug-ins are available for use by your app.

Uploading Your App

For Ionic View to run your app, you will need to upload it to Ionic.io with this command:

$ ionic upload

Your app will be uploaded to Ionic.io and the status will be displayed in the terminal:

Uploading app....
Saved app_id, writing to ionic.io.bundle.min.js...
Successfully uploaded (76059942)

Share your beautiful app with someone:
$ ionic share EMAIL

Saved api_key, writing to ionic.io.bundle.min.js...

Viewing Your App

Now simply launch the Ionic View mobile app, and it will automatically give you a list of apps that you have uploaded. You also have the ability to manually enter an app ID that’s been shared with you.

Figure 12-9.Ionic View’s available apps

Tap one of the app cards to bring up a pop up with possible actions. You can view the app, clear its local files, sync the local files with the latest upload from the Ionic Service, or remove it from your account.

Ionic View is a powerful tool to quickly test and view your app on a physical device without the need to compile it or formally install it.

Ionic Creator

There is one last item from Ionic that does need a brief mention. In exploring the Ionic websites, you may have seen a reference toIonic Creator(seeFigure 12-10). Before Drifty (the team behind most of Ionic) developed the Ionic Framework, they developed a visual design tool for jQuery Mobile called Codiqa. Ionic Creator is its descendant (in spirit).

Figure 12-10.Ionic Creator

This web-based tool allows you to design and author Ionic 1 applications all within your browser. The Creator team has done a fantastic job evolving this tool. There is a companion mobile app (a custom version of the Ionic View app) that allows you to seamlessly view your designs on an actual device. As of June 2017, Creator has released its first alpha version that supports Ionic v3 and above. The support is very limited for this initial release, but expect to see more features migrate over in the coming months.

Summary

The Ionic Services provide a lot of additional functionality beyond the core framework. Although it is a paid service, its tight integration with the framework might make it the right choice for your development needs.

results matching ""

    No results matching ""