Overview

Cloud Functions enables serverless computing. It provides the Function as a Service (FaaS) capabilities to simplify app development and O&M so your functions can be implemented more easily and your service capabilities can be built more quickly.

What You Will Create

In this codelab, you can build a function that can interact with your app using Cloud Functions. To do so, you will need to:

What You Will Learn

Development Environment and Skill Requirements

Device Requirements

An iPhone or a simulator for testing

To integrate Cloud Functions of AppGallery Connect, you must complete the following preparations:

Enabling Cloud Functions

  1. Sign in to AppGallery Connect and click My projects.
  2. Click the project for which you need to enable Cloud Functions.
  3. Go to Build > Cloud Functions.
  4. Click Enable now in the upper right corner of the page displayed.

You can use CocoaPods to integrate the Cloud Functions SDK in Xcode.

  1. Sign in to AppGallery Connect and click My projects.
  2. Click your project card and select an app for SDK integration from the app drop-down list on the top.
  3. Go to Project settings > General information. In the App information area, download the agconnect-services.plist file.
  4. Copy the agconnect-services.plist file to your project.
  5. Open the CLI and navigate to the location of the Xcode project. Then, create a Podfile. Skip this step if a Podfile already exists.
    cd project-directory pod init
  6. Add the pod ‘AGConnectFunction' dependency to the Podfile.
    target 'AGC-Function-1' do pod 'AGConnectFunction' end
  7. Install the pod and open the .xcworkspace file to view the project.
    pod install

    The following figure shows the result after installation.

Creating a Cloud Function

  1. Click New Function on the Cloud Functions page. The Create Function page is displayed.
  2. Define the function on the displayed page.
    • Enter a name and description of the function in Name and Description, respectively.
    • Enter the deployment information or retain the default values.
    • Set Code Entry Type to Edit code inline.
  3. In the Code File area, add the following code to the handler.js file.
    let myHandler = function(event, context, callback, logger) { var res = new context.HTTPResponse(context.env, { "res-type": "context.env", "faas-content-type": "json", }, "application/json", "200"); var year; if (event.body) { var _body = JSON.parse(event.body); year = _body.year; } else { year = event.year; } var body = { result: '' }; body.result = animal(year); res.body = body; context.callback(res); function animal(inputYear) { var resultString; if (!isNumber(inputYear)) { resultString = "input is not a number"; } else { var remainder = inputYear % 12; switch (remainder) { case 0: resultString = "Monkey"; break; case 1: resultString = "Chicken"; break; case 2: resultString = "Dog"; break; case 3: resultString = "Pig"; break; case 4: resultString = "Mouse"; break; case 5: resultString = "Cow"; break; case 6: resultString = "Tiger"; break; case 7: resultString = "Rabbit"; case 8: resultString = "Dragon"; break; case 9: resultString = "Snake"; break; case 10: resultString = "Horse"; break; case 11: resultString = "Sheep"; break; default: resultString = "No symbolic Animal"; } } return resultString; } function isNumber(input) { if (parseInt(input).toString == "NaN") { return false; } else { return true; } } }; module.exports.myHandler = myHandler;

Testing the Function

  1. On the Cloud Functions page, choose Functions from the navigation tree on the left. Click the name of the created function to access its details page. On the code tab page, click TestParam.
  2. On the createEvent tab page, add the following code to Event.
    { "year": 2020 }
  3. Click Submit and check whether the execution result is displayed as follows.

Adding a Trigger

  1. On the function list page, click the name of the function to go to its details page. If you click the function alias, the page for configuring the function alias will be displayed.
  2. Click + Add Trigger on the trigger tab page. The Add Trigger page is displayed.
  3. Configure information including Trigger Type. Here, HTTP and POST are selected for Trigger Type and Method, respectively.

    Parameter

    Description

    Trigger Type

    Set this parameter to HTTP.

    Method

    Set this parameter to POST, which is currently the only supported method by HTTP triggers.

    Authentication Type

    Authentication type of the HTTP trigger to be added.API client authentication (applicable to clients): gateway authentication on the client, which is applicable only to function calls from the app client.API client authentication (applicable to Server): gateway authentication on the cloud, which is applicable only to function calls from the app server.

    Url Decode

    Indicates whether to use the URLDecoder to decode the body of an HTTP-based function trigger request whose contentType is application/x-www-form-urlencoded and forward the decoded result to the function.

  4. Click Add and then Save.
  5. Save the suffix following the last slash (/) in the value of Trigger URL in the Details area as the trigger identifier of future app requests.

In this codelab, you can create a layout shown in the following figure in your iOS project. On the page, a result returned by a cloud function is displayed after a year is entered.

Sample code:

let yearTextField = UITextField(frame: CGRect(x: 60, y: 180, width: 200, height: 40)) let zodiacLabel = UILabel(frame: CGRect(x: 60, y: 260, width: 150, height: 60)) override func viewDidLoad() { super.viewDidLoad() let welcomeLabel = UILabel(frame: CGRect(x: 60, y: 100, width: 200, height: 60)) welcomeLabel.textColor = UIColor.darkGray welcomeLabel.text = "Please enter the year" self.view.addSubview(welcomeLabel) yearTextField.layer.borderWidth = 0.5 yearTextField.layer.borderColor = UIColor.darkGray.cgColor self.view.addSubview(yearTextField) zodiacLabel.textAlignment = .center zodiacLabel.textColor = UIColor.darkGray self.view.addSubview(zodiacLabel) let functionButton = UIButton(frame: CGRect(x: 60, y: 380, width: 140, height: 50)) functionButton.backgroundColor = UIColor.blue functionButton.setTitle("GET RESULT", for: .normal) functionButton.addTarget(self, action: #selector(triggerFunction), for: .touchUpInside) self.view.addSubview(functionButton) }
  1. Import AGConnectCore to the AppDelegate class of the app, and call AGCInstance.startUp in the didFinishLaunchingWithOptions method for initialization.
    import AGConnectCore func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool { AGCInstance.startUp() return true }
  2. In the tap event, call the cloud function to obtain the return value, and display the value on the page.
    @objc func triggerFunction() { let num = yearTextField.text ?? "" let callable = AGCFunction.getInstance().wrap("zodiac-$latest") callable.call(with: ["year":num]).onSuccess { (result) in let response = result?.value(with: NSDictionary.self) as! NSDictionary let zodiac = response["result"] as! String self.zodiacLabel.text = zodiac }.onFailure { (error) in } }
  1. In Xcode, run your app on a mobile phone or simulator.
  2. Enter a year, tap GET RESULT, and check whether the Chinese zodiac sign of the year is displayed.

Well done. You have successfully built your first app that integrates Cloud Functions and learned how to:

Code copied