When developing your enterprise mobile app that needs centralized hosting of data, use of cloud-native services such as Cloudant No-SQL Database for storing textual data and Object Storage service for storing image/video/audio data, allows you to quickly go from idea-conception to reality. The Mobile Foundation service available from IBM Cloud provides a scalable mobile access gateway for securely accessing those backend services, and it provides other essential mobile backend capabilities such as push notifications, app lifecycle management and app analytics.
This code pattern gives you step by step instructions for developing an Ionic/Cordova based hybrid mobile app that securely connects to Cloudant and Object Storage services via IBM MobileFoundation (aka MFP) service.
When you have completed this pattern, you will understand:
- How to authenticate users (through preemptive login) using MFP security adapater.
- How to write an MFP adapter that authenticates with Cloud Object Storage service and pass back the Authorization token to the mobile app.
- Recommended architectural patterns for coding the interaction between mobile app and Cloud Object Storage service.
- How to use imgcache.js in Ionic app for caching images fetched from Cloud Object Storage service.
- How to show Google Maps in Ionic app as well as capture user’s geo-location & image from camera.
- How to upload the captured image from mobile app to Cloud Object Storage service.
- How to fetch data from Cloudant service to mobile app via MFP adapter as well as post new data to Cloudant.
- How to customize the Ionic app logo and splash, and build the release apk for uploading to public/private app stores.
- User launches the mobile app, enters his/her credentials on the login screen and clicks
Login
. - Mobile app sends the user credentials to MFP server for validation.
- MFP server invokes the security adapter logic to validate user credentials and returns an appropriate response to the mobile app. For the sake of this demo, we will use a simple security adapter that returns success when password equals username.
- If user authentication succeeds, mobile app proceeds to show the home page. As part of this, it makes a call to MFP adapter to fetch the data from Cloudant NoSQL database.
- MFP adapter fetches the data from Cloudant and returns it to the mobile app. The data fetched from Cloudant will have references to the images stored in Cloud Object Storage.
- Mobile app makes a call to MFP adapter to get the Authorization token for interacting with Cloud Object Storage service.
- MFP adapter makes a call to Cloud Object Storage service's token manager endpoint to get the Authorization token and returns it to the mobile app.
- Mobile app initializes image-caching plugin and asks it to use an HTTP header of
Authorization=<value returned from MFP adapter>
while fetching images. Mobile app displays the data obtained from MFP adapter as a list of items. The image caching plugin running on the mobile app downloads and caches images from Cloud Object Storage. - User clicks on one of the list item to see more details. A detail page is shown consisting of image and geo-location marked inside Google Maps.
- Back in the home page, user clicks on
+
button to report a new civic problem. A new page is shown where user can enter a description for the new civic problem as well as capture image and geo-location of the problem spot. User clicks onSubmit
button. - Mobile app uploads the textual data to Cloudant NoSQL DB via MFP Adapter.
- Mobile app creates a thumbnail image by resizing the captured image and uploads both the captured image and thumbnail to Cloud Object Storage.
- Other users who click on refresh button on the home page (and those who log in afresh) are shown the updated list of problem reports.
- Cloudant NoSQL DB: A fully managed data layer designed for modern web and mobile applications that leverages a flexible JSON schema.
- Cloud Object Storage: A highly scalable cloud storage service, designed for high durability, resiliency and security.
- Mobile Foundation: A scalable mobile access gateway powered by the market-leading IBM Mobile Foundation Technology. The service offers a comprehensive set of mobile backend capabilities such as, App life cycle, Push, Analytics, Feature Toggle, Security and Authentication and offline synch.
- Mobile: Systems of engagement are increasingly using mobile technology as the platform for delivery.
- 5.1 Clone repo
- 5.2 Update App ID, Name and Description
- 5.3 Specify Cloudant credentials in MFP adapter
- 5.4 Specify Cloud Object Storage credentials in MFP Adapter
- 6.1 Build and Deploy the MFP adapters
- 6.2 Register the MyWard app to MFP server
- 6.3 Map MyWardData's protecting scope to UserLogin security check
- 6.4 Test the MyWardData adapter
- 7.1 Install Android Studio and Android SDK platform
- 7.2 Enable developer options and USB debugging on your Android phone
- 7.3 Enable Android platform for Ionic application
- 7.4 Build/Run the Ionic application on Android phone
- 7.5 Update App Logo and Splash
- 7.6 Build APK for uploading to Google Play Store
- Install Node.js by downloading the setup from https://nodejs.org/en/ (Node.js 8.x or above)
$ node --version
v8.6.0
- Install Cordova
$ sudo npm install -g cordova
$ cordova --version
7.0.1
Note: If you are on Windows, instead of using sudo, run the above command (and the ones below) in a command prompt opened in administrative mode.
- Install Ionic
$ sudo npm install -g ionic
$ ionic --version
3.19.0
- Install IBM MobileFirst Platform CLI
$ sudo npm install -g mfpdev-cli
$ mfpdev --version
8.0.0-2017091111
- Install GIT https://git-scm.com/downloads
$ git --version
git version 2.9.3 ...
- Install Maven:
On Mac, you can use
brew install
for installing Maven as shown below:
$ /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"
$ brew install maven
$ mvn --version
Apache Maven 3.5.0 ...
- Install Java SDK from http://www.oracle.com/technetwork/java/javase/downloads/index.html
$ java -version
java version "1.8.0_101"
-
Install an IDE for TypeScript such as Atom on Mac.
After installing Atom, install TypeScript plugin for Atom as shown below.
apm install atom-typescript
- Log in to IBM Cloud Dashboard and create Cloudant NoSQL DB service.
- From the welcome page of Cloudant service that you just created, launch the Cloudant Dashboard.
- In the Cloudant dashboard, click on Databases.
- Click on Create Database. Specify name of database as
myward
as shown below. Click Create.
Once the database is created, the dashboard will update to show the documents inside myward
database (which, as expected, will be empty to begin with).
- Click Create Document. Under document content, after the auto populated
_id
field, enter grievance details as shown below. Please note that you need to put a comma (,) after the auto populated_id
field.
{
"_id": "7fc63023799dfda9582609e75127b4fa",
"reportedBy": "[email protected]",
"reportedDateTime": "20171125_152627",
"picture": {
"large": "IMG-20171125-WA0012.jpeg",
"thumbnail": "thumbnail_IMG-20171125-WA0012.jpg"
},
"problemDescription": "Car parking on busy market road chocking movement of other vehicles and pedestrians",
"geoLocation": {
"type": "Point",
"coordinates": [
77.7893168,
13.0773568
]
},
"address": "Basaveshwara Temple road (behind Market Road), Hosakote, Bangalore 562114"
}
Click Create Document to create/save the document.
- Repeat the above steps and create documents for the remaining grievances as shown in SampleData/MyWardGrievances.json.
- In the Cloudant dashboard, under
myward
database, click on Permissions and then click on Generate API Key as shown in the snapshot below. - Make a note of the Key and Password generated.
- The newly added key would get listed under Cloudant users with default permission of reader only. Select the checkbox under writer next to the new key to give it write permission as well.
-
In the IBM Cloud Dashboard, click on
Catalog
and select Object Storage service underInfrastructure
->Storage
. Click onCreate
as shown below. -
The IBM Cloud Object Storage dashboard will get shown. In the
Buckets and objects
page, click onCreate bucket
. Give a unique name for the bucket. Leave the default selections as-is for Resiliency (Cross Region
), Location (us-geo
) and Storage class (Standard
), and click onCreate
as shown below. -
The Bucket overview page for the newly created bucket will get shown. Click on
Add objects
. InUpload obects
dialog, click onAdd files
and select all the images under SampleData directory (the six images and their thumbnails). ClickOpen
. Click onUpload
as shown below. Once upload is complete, you should see the images listed under your bucket.
-
Create Service ID
- In a separate browser tab/window, launch the IBM Cloud Identity & Access Management dashboard using URL https://console.bluemix.net/iam/.
- In case you have multiple IBM Cloud accounts, then select the target Account, Region, Organization and Space.
- Under
Identity & Access
(on the left side of the page), selectService IDs
and clickCreate
. Give a name and description, and clickCreate
. - Make a note of the Service ID as shown below.
-
Add Cloud Object Storage Writer role to that service ID
- Back in IBM Cloud Object Storage dashboard, select
Bucket permissions
underBuckets and objects
. - Click on
Service IDs
tab. UnderSelect a service ID
, select the service ID created in the above step. UnderAssign a role to this service ID for this bucket
, selectWriter
. ClickCreate policy
as shown below. You should get a confirmation dialog saying “Service permission created“.
- Back in IBM Cloud Object Storage dashboard, select
-
Create API Key
- Back in IBM Cloud Identity & Access Management dashboard, under
Service IDs
, click on the service ID created earlier. UnderAccess policies
, you should see theWriter
role for your bucket. - Click on
API keys
tab and then click onCreate
button. In theCreate API key
dialog, give a name and description for the API key and click onCreate
. You should get a confirmation dialog sayingAPI key successfully created
as shown below. - Click on
Download
and save the API key as shown below. Note: This is the only time you will see the key. You cannot retrieve it later. - Finally click on
Close
.
- Back in IBM Cloud Identity & Access Management dashboard, under
In the IBM Cloud Dashboard, click on Catalog
and select Mobile Foundation service under Platform
-> Mobile
. Click on Create as shown below.
In the Mobile Foundation service overview page that gets shown, click on Service credentials
. Expand View credentials
and make a note of the url
, user
and password
as shown below.
- Back on your local machine, configure MFP CLI to work with Mobile Foundation server by running following command in console.
$ mfpdev server add
? Enter the name of the new server profile: Cloud-MFP
? Enter the fully qualified URL of this server: https://mobilefoundation-71-hb-server.mybluemix.net:443
? Enter the MobileFirst Server administrator login ID: admin
? Enter the MobileFirst Server administrator password: **********
? Save the administrator password for this server?: Yes
? Enter the context root of the MobileFirst administration services: mfpadmin
? Enter the MobileFirst Server connection timeout in seconds: 30
? Make this server the default?: Yes
Verifying server configuration...
The following runtimes are currently installed on this server: mfp
Server profile 'Cloud-MFP' added successfully.
$ mfpdev server info
Name URL
--------------------------------------------------------------------------------------
Cloud-MFP https://mobilefoundation-71-hb-server.mybluemix.net:443 [Default]
--------------------------------------------------------------------------------------
Note: For Enter the fully qualified URL of this server:
, enter the url
mentioned in credentials followed by :443
(the default HTTPS port).
$ git clone https://github.com/IBM/Ionic-MFP-App.git
$ cd Ionic-MFP-App
Update IonicMobileApp/config.xml
as below. Change id
, name
, description
and author
details appropriately.
<?xml version='1.0' encoding='utf-8'?>
<widget id="org.mycity.myward" version="0.0.1" xmlns="http://www.w3.org/ns/widgets" xmlns:cdv="http://cordova.apache.org/ns/1.0" xmlns:mfp="http://www.ibm.com/mobilefirst/cordova-plugin-mfp">
<name>MyWard</name>
<description>Get your civic issues resolved by posting through this app.</description>
<author email="[email protected]" href="https://developer.ibm.com/code/author/shivahr/">Shiva Kumar H R</author>
...
Open MobileFoundationAdapters/MyWardData/src/main/adapter-resources/adapter.xml
and update the following properties to point to the Cloudant database created in Step 2.
- Update
key
andpassword
with the Cloudant API key as generated in Step 2.2. - For property
account
, specify the Cloudant dashboard URL portion upto (and including) -bluemix.cloudant.com as shown in the snapshot of Step 2.2. - For property
DBName
, leave the default value ofmyward
as-is.
<mfp:adapter name="MyWardData" ...>
<property name="account" displayName="Cloudant account" defaultValue=""/>
<property name="key" displayName="Cloudant key" defaultValue=""/>
<property name="password" displayName="Cloudant password" defaultValue=""/>
<property name="DBName" displayName="Cloudant DB name" defaultValue="myward"/>
...
</mfp:adapter>
Open MobileFoundationAdapters/MyWardData/src/main/adapter-resources/adapter.xml
and update the following properties to point to the Cloud Object Storage created in Step 3.
- Specify value for
bucketName
as created in Step 3.1. - Specify
serviceId
andapiKey
created in Step 3.2. - While creating the bucket in Step 3.1, if you selected a different Location/Resiliency, then update the
endpointURL
as per the specification in https://console.bluemix.net/docs/services/cloud-object-storage/basics/endpoints.html#select-regions-and-endpoints.
<mfp:adapter name="MyWardData" ...>
...
<property name="endpointURL" displayName="Cloud Object Storage Endpoint Public URL" defaultValue="https://s3-api.us-geo.objectstorage.softlayer.net"/>
<property name="bucketName" displayName="Cloud Object Storage Bucket Name" defaultValue=""/>
<property name="serviceId" displayName="Cloud Object Storage Service ID" defaultValue="" />
<property name="apiKey" displayName="Cloud Object Storage API Key" defaultValue=""/>
</mfp:adapter>
Build and deploy UserLogin Adapter as below.
$ cd MobileFoundationAdapters/
$ cd UserLogin
$ mfpdev adapter build
$ mfpdev adapter deploy
Note: In Step 4, if you specified No
to Make this server the default?
, then you need to specify the name of your server profile (Cloud-MFP
in our case) at the end of mfpdev adapter deploy
command as shown below.
$ mfpdev adapter deploy Cloud-MFP
Build and deploy MyWardData Adapter as below.
$ cd ../MyWardData/
$ mfpdev adapter build
$ mfpdev adapter deploy
$ cd ../../IonicMobileApp/
$ mfpdev app register
Verifying server configuration...
Registering to server:'https://mobilefoundation-71-hb-server.mybluemix.net:443' runtime:'mfp'
Updated config.xml file located at: .../Ionic-MFP-App/IonicMobileApp/config.xml
Run 'cordova prepare' to propagate changes.
Registered app for platform: android
Note: In Step 4, if you specified No
to Make this server the default?
, then you need to specify the name of your server profile (Cloud-MFP
in our case) at the end of mfpdev app register
command as shown below.
$ mfpdev app register Cloud-MFP
Propogate changes by running cordova prepare
$ cordova prepare
Launch MFP Dashboard as below:
- In the IBM Cloud dashboard, under Cloud Foundry Services, click on the Mobile Foundation service you created in Step 4. The service overview page that gets shown, will have the MFP dashboard embedded within it. You can also open the MFP dashboard in a separate browser tab by appending
/mfpconsole
to the url mentioned in Step 4. - Inside the MFP dashboard, in the list on the left, you will see the
MyWard
application, andMyWardData
andUserLogin
adapters listed.
Verify MFP Adapter configuration as below:
- Inside the MFP dashboard, click on the
MyWardData
adapter. UnderConfigurations
tab, you should see the various properties we specified in Step 5.3 and Step 5.4 for acccessing Cloudant database and Cloud Object Storage as shown below. As an alternative to specifying those property values inMobileFoundationAdapters/MyWardData/src/main/adapter-resources/adapter.xml
as previously shown in Step 5.3 and Step 5.4, you can deploy the adapters with emptydefaultValue
, and once the adapter is deployed, change the values on this page.
- Click on
Resources
tab. You should see the various REST APIs exposed byMyWardData
adapter as shown below. TheSecurity
column should show the protecting scopeRestrictedData
against each REST method.
Map RestrictedData
scope to UserLogin
security check as below:
- In the MFP dashboard, under
Applications
click onMyWard
application. Click onAndroid
and click onSecurity
tab. Click onNew
button underScope-Elements Mapping
as shown below. - Specify
Scope element
asRestrictedData
, and underCustom Security Checks
selectUserLogin
as shown below. Click onAdd
. The new mapping should get created and shown underScope-Elements Mapping
.
- Repeat above steps for
Applications
->MyWard
->iOS
in case you add Cordova platform for iOS as well.
Create temporary credentials to test adapter REST API as below:
- Inside the MFP dashboard, click on
Runtime Settings
. Click onConfidential Clients
. Then click onNew
. - In the form that pops up, specify values for
ID
andSecret
as shown in snapshot below. ForAllowed Scope
enter ** and click onAdd
. Finally click onSave
.
Test adapter REST API as below:
- Inside the MFP dashboard, click on the
MyWardData
adapter. Click onResources
and then click onView Swagger Docs
. The Swagger UI for adapter REST APIs will get shown in a new window/tab. - Inside the Swagger UI, click on
Expand Operations
. - To test the
GET /
API, first click onOFF
toggle button to enable authentication. SelectDefault Scope
and click onAuthorize
as shown below. Enter theID
andSecret
created above againstUsername
andPassword
. ClickOK
. If authentication is successful, the toggle button will switch toON
position.
- Now click on
Try it out
button to run theGET /
API. The API response should get shown in theResponse Body
as shown in snapshot below.
- The GET API on
/objectStorage
should return a JSON object containingbaseUrl
andauthorizationHeader
as shown below.
Delete the temporary credentials after testing adapter REST API as below:
- Inside the MFP dashboard, click on
Runtime Settings
. Click onConfidential Clients
. - Delete the
Client ID
created previously.
- Download and install Android Studio from https://developer.android.com/studio/index.html
- Install Android SDK Platform 23 (or higher)
- Launch Android Studio.
- Click on Configure -> SDK Manager
- Under SDK Platforms, select Android 6.0 (Marshmallow) API Level 23. Click Apply and then click OK. This will install Android SDK Platform on your machine.
- Enable USB debugging on your Android phone as per the steps in https://developer.android.com/studio/debug/dev-options.html
- Launch the Settings app on your phone. Select About Device -> Software Info . Tap Build number 7 times to enable developer options.
- Return to Settings list. Select Developer options and enable USB debugging.
- If you are developing on Windows, then you need to install the appropriate USB driver as per instructions in https://developer.android.com/studio/run/oem-usb.html.
- Connect the Android phone to your development machine by USB cable, and accept allow access on your phone.
$ ionic cordova platform add [email protected]
> cordova platform add [email protected] --save
...
Note: Make sure the Cordova platform version being added is supported by the MobileFirst plug-ins. Site https://mobilefirstplatform.ibmcloud.com/tutorials/en/foundation/8.0/application-development/sdk/cordova/ lists the supported levels.
$ cordova platform version
Installed platforms:
android 6.3.0
Available platforms:
blackberry10 ~3.8.0 (deprecated)
browser ~4.1.0
ios ~4.4.0
osx ~4.0.1
webos ~3.7.0
Cordova Android 6.3.0 targets the latest Android API level of API 26. If you want to target API 23 instead, then edit IonicMobileApp/config.xml
and add preference for android-targetSdkVersion
as shown below.
<preference name="android-minSdkVersion" value="16" />
<preference name="android-targetSdkVersion" value="23" />
- Build Android application
$ ionic cordova build android
- Run application on Android device
$ ionic cordova run android
Reference: Automating Icons and Splash Screens https://blog.ionic.io/automating-icons-and-splash-screens/
Copy your desired app icon to IonicMobileApp/resources/icon.png
and app splash to IonicMobileApp/resources/splash.png
.
$ cd ../IonicMobileApp
$ ionic cordova resources
For running ionic cordova resources
command, you would need to sign up on ionicframework.com and specify the credentials on the command line.
- Add following lines at the end of
IonicMobileApp/platforms/android/proguard-project-mfp.txt
:
-dontwarn okhttp3.internal.huc.**
-keep class plugin.google.maps.** { *; }
- Create release build as below:
$ cd ../IonicMobileApp
$ ionic cordova build android --prod --release
- Zip align release build as below:
$ cd ./platforms/android/build/outputs/apk/
$ ls
android-release-unsigned.apk
$ <Android-Home>/sdk/build-tools/25.0.2/zipalign -v -p 4 android-release-unsigned.apk android-release-unsigned-aligned.apk
$ ls
android-release-unsigned-aligned.apk android-release-unsigned.apk
where, <Android-Home>
points to the location of your Android Home directory. On Mac, this is usually /Users/<username>/Library/Android/
.
- Create self signing certificate as below:
$ keytool -genkey -v -keystore my-release-key.jks -keyalg RSA -keysize 2048 -validity 10000 -alias my-alias
$ ls
android-release-unsigned-aligned.apk android-release-unsigned.apk my-release-key.jks
- Self sign APK as below:
$ <Android-Home>/sdk/build-tools/25.0.2/apksigner sign --ks my-release-key.jks --out myward.apk android-release-unsigned-aligned.apk
Keystore password for signer #1:
$ ls
android-release-unsigned-aligned.apk my-release-key.jks
android-release-unsigned.apk myward.apk
$
- Distrubute
myward.apk
by uploading to Google Play Store or to your company's internal App store.
-
Install Google Chrome
-
Open Google Chrome. Open URL chrome://inspect/#devices
-
Under Devices, click on inspect below your connected device.