subcollection | copyright | lastupdated | lasttested | ||
---|---|---|---|---|---|
solution-tutorials |
|
2019-10-07 |
2019-06-04 |
{:java: #java .ph data-hd-programlang='java'} {:swift: #swift .ph data-hd-programlang='swift'} {:ios: data-hd-operatingsystem="ios"} {:android: data-hd-operatingsystem="android"} {:shortdesc: .shortdesc} {:new_window: target="_blank"} {:codeblock: .codeblock} {:screen: .screen} {:tip: .tip} {:pre: .pre}
{: #serverless-mobile-backend}
In this tutorial, you will learn how to use {{site.data.keyword.openwhisk}} along with Cognitive and Data services to build a serverless backend for a mobile application. {:shortdesc}
Not all mobile developers have experience managing server-side logic, or a server to start with. They would prefer to focus their efforts on the app they are building. Now what if they could reuse their existing development skills to write their mobile backend?
{{site.data.keyword.openwhisk_short}} is a serverless event-driven platform. As highlighted in this example, the actions you deploy can easily be turned into HTTP endpoints as web actions to build a web application backend API. A web application being a client to the REST API, it is easy to take this example a step further and apply the same approach to build a backend for a mobile app. And with {{site.data.keyword.openwhisk_short}}, mobile developers can write the actions in the same language used for their mobile app, Java for Android, and Swift for iOS.
This tutorial is configurable based on your target platform. You are currently viewing the documentation for the iOS / Swift version of this tutorial. Use the tab at the top of this documentation to select the Android / Java version of this tutorial. {: swift}
This tutorial is configurable based on your target platform. You are currently viewing the documentation for the Android / Java version of this tutorial. Use the tab at the top of this documentation to select the iOS / Swift version of this tutorial. {: java}
{: #objectives}
- Deploy a serverless mobile backend with {{site.data.keyword.openwhisk_short}}.
- Add user authentication to a mobile app with {{site.data.keyword.appid_short}}.
- Analyze user feedback with {{site.data.keyword.toneanalyzershort}}.
- Send notifications with {{site.data.keyword.mobilepushshort}}.
{: #services}
This tutorial uses the following runtimes and services:
- {{site.data.keyword.openwhisk_short}}
- {{site.data.keyword.appid_short}}
- {{site.data.keyword.cloudant_short_notm}}
- {{site.data.keyword.toneanalyzershort}}
- {{site.data.keyword.mobilepushshort}}
This tutorial may incur costs. Use the Pricing Calculator to generate a cost estimate based on your projected usage.
{: #architecture}
The application shown in this tutorial is a feedback app that smartly analyses the tone of the feedback text and appropriately acknowledges the customer through a {{site.data.keyword.mobilepushshort}}.
![](images/solution11/Architecture.png)
- The user authenticates against {{site.data.keyword.appid_short}}. {{site.data.keyword.appid_short}} provides access and identification tokens.
- Further calls to the backend API include the access token.
- The backend is implemented with {{site.data.keyword.openwhisk_short}}. The serverless actions, exposed as Web Actions, expect the token to be sent in the request headers and verify its validity (signature and expiration date) before allowing access to the actual API.
- When the user submits a feedback, the feedback is stored in {{site.data.keyword.cloudant_short_notm}}
- The feedback text is processed with {{site.data.keyword.toneanalyzershort}}.
- Based on the analysis result, a notification is sent back to the user with {{site.data.keyword.mobilepushshort}}.
- The user receives the notification on the device.
{: #prereqs}
This tutorial uses the {{site.data.keyword.Bluemix_notm}} command line tool to provision resources and deploy code. Make sure to install the ibmcloud
command line tool.
- {{site.data.keyword.Bluemix_notm}} Developer Tools - Script to install ibmcloud CLI and required plug-ins (Cloud Foundry and {{site.data.keyword.openwhisk_short}})
Additionally you will need the following software and accounts:
-
Java 8
-
Android Studio 2.3.3
-
Google Developer account to configure Firebase Cloud Messaging
-
Bash shell, cURL {: java}
-
Xcode
-
Apple Developer account to configure Apple Push Notification Service
-
Bash shell, cURL {: swift}
In this tutorial, you will configure push notifications for the application. The tutorial assumes you have completed the basic {{site.data.keyword.mobilepushshort}} tutorial for either Android or iOS and you are familiar with the configuration of Firebase Cloud Messaging or Apple Push Notification Service. {:tip}
For Windows 10 users to work with the command line instructions, we recommend installing the Windows Subsystem for Linux and Ubuntu as described in this article. {: tip} {: java}
The repository contains both the mobile application and the {{site.data.keyword.openwhisk_short}} actions code.
-
Checkout the code from the GitHub repository
git clone https://github.com/IBM-Cloud/serverless-followupapp-android
{: pre} {: java}
git clone https://github.com/IBM-Cloud/serverless-followupapp-ios
{: pre} {: swift}
-
Review the code structure
File | Description |
---|---|
actions | Code for the {{site.data.keyword.openwhisk_short}} actions of the serverless mobile backend |
android | Code for the mobile application |
deploy.sh | Helper script to install, uninstall, update the {{site.data.keyword.openwhisk_short}} trigger, actions, rules |
{: java} |
File | Description |
---|---|
actions | Code for the {{site.data.keyword.openwhisk_short}} actions of the serverless mobile backend |
followupapp | Code for the mobile application |
deploy.sh | Helper script to install, uninstall, update the {{site.data.keyword.openwhisk_short}} trigger, actions, rules |
{: swift} |
{: #provision_services}
In this section, you will provision the services used by the application. You can choose to provision the services from the {{site.data.keyword.Bluemix_notm}} catalog or using the ibmcloud
command line.
It is recommended that you create a new space to provision the services and deploy the serverless backend. This helps to keep all the resources together.
- Go to the {{site.data.keyword.Bluemix_notm}} catalog
- Create a {{site.data.keyword.cloudant_short_notm}} service with the Lite plan. Set the name to serverlessfollowup-db.
- Create a {{site.data.keyword.toneanalyzershort}} service with the Standard plan. Set the name to serverlessfollowup-tone.
- Create an {{site.data.keyword.appid_short}} service with the Graduated tier plan. Set the name to serverlessfollowup-appid.
- Create a {{site.data.keyword.mobilepushshort}} service with the Lite plan. Set the name to serverlessfollowup-mobilepush.
With the command line, run the following commands to provision the services and retrieve their credentials:
Set the location where services should be created:
REGION=us-south
{: pre}
ibmcloud resource service-instance-create serverlessfollowup-db cloudantnosqldb lite $REGION -p '{"legacyCredentials": true}'
{: pre}
ibmcloud resource service-key-create serverlessfollowup-db-for-cli Manager --instance-name serverlessfollowup-db
{: pre}
ibmcloud resource service-instance-create serverlessfollowup-tone tone-analyzer lite $REGION
{: pre}
ibmcloud resource service-key-create serverlessfollowup-tone-for-cli Writer --instance-name serverlessfollowup-tone
{: pre}
ibmcloud resource service-instance-create serverlessfollowup-appid appid lite $REGION
{: pre}
ibmcloud resource service-key-create serverlessfollowup-appid-for-cli Writer --instance-name serverlessfollowup-appid
{: pre}
ibmcloud resource service-instance-create serverlessfollowup-mobilepush imfpush lite $REGION
{: pre}
ibmcloud resource service-key-create serverlessfollowup-mobilepush-for-cli Writer --instance-name serverlessfollowup-mobilepush
{: pre}
{: #push_notifications}
When a user submits a new feedback, the application will analyze this feedback and send back a notification to the user. The user may have moved to another task, or may not have the mobile app started so using push notifications is a good way to communicate with the user. The {{site.data.keyword.mobilepushshort}} service makes it possible to send notifications to iOS or Android users via one unified API. In this section, you will configure the {{site.data.keyword.mobilepushshort}} service for your target platform.
{: java}
- In the Firebase console, create a new project. Set the name to serverlessfollowup
- Navigate to the Project Settings
- Under the General tab, add two applications:
- one with the package name set to: com.ibm.mobilefirstplatform.clientsdk.android.push
- and one with the package name set to: serverlessfollowup.app
- Download the
google-services.json
containing the two defined applications from Firebase console and place this file in theandroid/app
folder of the checkout directory. - Find the Sender ID and Server Key (also called API Key later on) under the Cloud Messaging tab.
- In the Push Notifications service dashboard, set the value of the Sender ID and API Key. {: java}
{: swift}
- Go to the Apple Developer portal and Register an App ID.
- Create a development and distribution APNs SSL certificate.
- Create a development provisioning profile.
- Configure the {{site.data.keyword.mobilepushshort}} service instance on {{site.data.keyword.Bluemix_notm}}. Refer to Obtain APNs credentials and configure {{site.data.keyword.mobilepushshort}} service for detailed steps. {: swift}
{: #serverless_backend}
With all the services configured, you can now deploy the serverless backend. The following {{site.data.keyword.openwhisk_short}} artifacts will be created in this section:
Artifact | Type | Description |
---|---|---|
serverlessfollowup |
Package | A package to group the actions and to keep all service credentials |
serverlessfollowup-cloudant |
Package Binding | Bound to the built-in {{site.data.keyword.cloudant_short_notm}} package |
serverlessfollowup-push |
Package Binding | Bound to the {{site.data.keyword.mobilepushshort}} package |
auth-validate |
Action | Validates the access and identification tokens |
users-add |
Action | Persists the user information (id, name, email, picture, device id) |
users-prepare-notify |
Action | Formats a message to use with {{site.data.keyword.mobilepushshort}} |
feedback-put |
Action | Stores a user feedback in the database |
feedback-analyze |
Action | Analyzes a feedback with {{site.data.keyword.toneanalyzershort}} |
users-add-sequence |
Sequence exposed as Web Action | auth-validate and users-add |
feedback-put-sequence |
Sequence exposed as Web Action | auth-validate and feedback-put |
feedback-analyze-sequence |
Sequence | read-document from {{site.data.keyword.cloudant_short_notm}}, feedback-analyze , users-prepare-notify and sendMessage with {{site.data.keyword.mobilepushshort}} |
feedback-analyze-trigger |
Trigger | Called by {{site.data.keyword.openwhisk_short}} when a feedback is stored in the database |
feedback-analyze-rule |
Rule | Links the trigger feedback-analyze-trigger with the sequence feedback-analyze-sequence |
{: java}
-
From the root of the checkout directory, compile the actions code {: java}
./android/gradlew -p actions clean jar
{: pre} {: java}
{: java}
-
Copy template.local.env to local.env
cp template.local.env local.env
-
Get the credentials for {{site.data.keyword.cloudant_short_notm}}, {{site.data.keyword.toneanalyzershort}}, {{site.data.keyword.mobilepushshort}} and {{site.data.keyword.appid_short}} services from the {{site.data.keyword.Bluemix_notm}} dashboard (or the output of the ibmcloud commands we ran before) and replace placeholders in
local.env
with corresponding values. These properties will be injected into a package so that all actions can get access to the database. -
Deploy the actions to {{site.data.keyword.openwhisk_short}}.
deploy.sh
loads the credentials fromlocal.env
to create the {{site.data.keyword.cloudant_short_notm}} databases (users, feedback and moods) and deploy the {{site.data.keyword.openwhisk_short}} artifacts for the application../deploy.sh --install
{: pre}
You can use
./deploy.sh --uninstall
to remove the {{site.data.keyword.openwhisk_short}} artifacts once you have completed the tutorial. {: tip}
{: swift}
-
Copy template.local.env to local.env
cp template.local.env local.env
-
Get the credentials for {{site.data.keyword.cloudant_short_notm}}, {{site.data.keyword.toneanalyzershort}}, {{site.data.keyword.mobilepushshort}} and {{site.data.keyword.appid_short}} services from the {{site.data.keyword.Bluemix_notm}} dashboard (or the output of the ibmcloud commands we ran before) and replace placeholders in
local.env
with corresponding values. These properties will be injected into a package so that all actions can get access to the database. -
Deploy the actions to {{site.data.keyword.openwhisk_short}}.
deploy.sh
loads the credentials fromlocal.env
to create the {{site.data.keyword.cloudant_short_notm}} databases (users, feedback and moods) and deploy the {{site.data.keyword.openwhisk_short}} artifacts for the application../deploy.sh --install
{: pre}
You can use
./deploy.sh --uninstall
to remove the {{site.data.keyword.openwhisk_short}} artifacts once you have completed the tutorial. {: tip}
{: #mobile_app}
Our {{site.data.keyword.openwhisk_short}} actions are ready for our mobile app. Before running the mobile app, you need to configure its settings to target the services you created.
-
With Android Studio, open the project located in the
android
folder of your checkout directory. -
Edit
android/app/src/main/res/values/credentials.xml
and fill in the blanks with values from credentials. You will need the {{site.data.keyword.appid_short}}tenantId
, the {{site.data.keyword.mobilepushshort}}appGuid
andclientSecret
and the organization and space names where the {{site.data.keyword.openwhisk_short}} have been deployed. For API host, launch command prompt or terminal and run the commandibmcloud fn property get --apihost
{: pre}
-
In
android/app/src/main/java/serverlessfollowup/app/LoginActivity.java
and inandroid/app/src/main/java/serverlessfollowup/app/LoginAndRegistrationListener.java
, update the value of the constantregion
to the location where the services were created. -
Build the project.
-
Start the application on a real device or with an emulator. For the emulator to receive push notifications, make sure to pick an image with the Google APIs and to log in with a Google account within the emulator. {: tip}
-
Watch the {{site.data.keyword.openwhisk_short}} in the background
ibmcloud fn activation poll
{: pre}
-
In the application, select Log in to authenticate with a Facebook or Google account. Once logged in, type a feedback message and press the Send Feedback button. Few seconds after the feedback has been sent, you should receive a push notifications on the device. The notification text can be customized by modifying the template documents in the
moods
database in the {{site.data.keyword.cloudant_short_notm}} service instance. Use the View token button to inspect the access and identification tokens generated by {{site.data.keyword.appid_short}} upon login. {: java} -
Push client SDK and other SDKs are available on CocoaPods and Carthage. For this solution, let's use CocoaPods.
-
Open Terminal and
cd
intofollowupapp
folder. Run the below command to install the required dependencies.pod install
{: pre}
-
Open the file with
.xcworkspace
extension located under thefollowupapp
folder of your checkout directory to launch your code in Xcode. -
Edit
BMSCredentials.plist file
and fill in the blanks with values from credentials. You will need the {{site.data.keyword.appid_short}}tenantId
, the {{site.data.keyword.mobilepushshort}}appGuid
andclientSecret
and the organization and space names where the {{site.data.keyword.openwhisk_short}} have been deployed. For API host, launch terminal and run the commandibmcloud fn property get --apihost
{: pre}
-
Open
AppDelegate.swift
and update the push notifications service(BMSClient) region and AppID region depending on the location in which your service instances are created. -
Build the project.
-
Start the application on a real device or with a simulator.
-
Watch the {{site.data.keyword.openwhisk_short}} in the background by running the below command on a Terminal.
ibmcloud fn activation poll
{: pre}
-
In the application, select Log in to authenticate with a Facebook or Google account. Once logged in, type a feedback message and press the Send Feedback button. Few seconds after the feedback has been sent, you should receive a push notifications on the device. The notification text can be customized by modifying the template documents in the
moods
database in the {{site.data.keyword.cloudant_short_notm}} service instance. Use the View token button to inspect the access and identification tokens generated by {{site.data.keyword.appid_short}} upon login. {: swift}
-
Use
deploy.sh
to remove the {{site.data.keyword.openwhisk_short}} artifacts:./deploy.sh --uninstall
{: pre}
-
Delete the {{site.data.keyword.cloudant_short_notm}}, {{site.data.keyword.appid_short}}, {{site.data.keyword.mobilepushshort}} and {{site.data.keyword.toneanalyzershort}} services from the {{site.data.keyword.Bluemix_notm}} console.
-
{{site.data.keyword.appid_short}} provides a default configuration to help with the initial set up of your identity providers. Prior to publishing your app, update the configuration to your own credentials. You will also be able to customize the login widget.
-
When you create an OpenWhisk Swift action with a Swift source file(.swift files under
actions
folder), it has to be compiled into a binary before the action is run. Once done, subsequent calls to the action are much faster until the container that holds your action is purged. This delay is known as the cold-start delay. To avoid the cold-start delay, you can compile your Swift file into a binary and then upload to OpenWhisk in a zip file. As you need the OpenWhisk scaffolding, the easiest way to create the binary is to build it within the same environment it runs in. refer Package an Action as a Swift executable for further steps. {: swift}