Data services

Version 2.0 - April 2021

Introduction

One of the core steps of building a mobile application is sourcing data from different external sources. In practice, there are different options

  • REST endpoints (JSON over HTTP(S) )
  • MQTT endpoints (Use of MQTT messaging technology)
  • WebSockets
  • SOAP endpoints
  • proprietary endpoints

We describe some of the options in the following chapter

Calling a REST service

You use Swift Foundation functionality to call HTTP endpoints. Thanks to SCADE's support of Swift Foundation on Android, you can use the exact same code.

import Foundation

class HttpClientDemo {

  func post(plainTextData:String) {

    // define target
    let url = URL(string: "https://httpbin.org/post")!

    //create the session object
    let session = URLSession.shared

    //now create the URLRequest object using the url object
    var request = URLRequest(url: url)

    // set to post - don't know why apple guys didn't use constants
    request.httpMethod = "POST"
    request.httpBody = plainTextData.data(using: .utf8)

    // create task
    let task = session.dataTask(
      with: request,
      completionHandler: { data, response, error in
        print(response!)
        print("performed HTTPS post successfully")

        let str = String(data: data!, encoding: .utf8)
        print(str!)
      })
    // Resume task to execute it
    task.resume()

  }
}

Pretty easy :

Links

ArticleLink
Discussion of calling HTTP on StackOverflowlink