Skip to Content
Author's profile photo Craig Cmehil

January Tip: Apple Swift and SAP HANA OData

Recently I was working on some sample apps and demos around using Mac OS, iOS, etc and getting data to and from my SAP HANA OData services I created in the SAP HANA Cloud Platform.

Using the basics from the following tutorials I was created an OData service that allowed me to read data from my tables as well as send data to the tables. This of course allowed me to create multiple types of tables and services for multiple different purposes.

I won’t bore everyone with the details of what I was working on, needless to say that information will come much later in future posts. Maps, Geo locations, etc. all fun stuff that I hope will expand into some cool demos later on.

The challenge I had and what I wanted to share here, was how to use Apple Swift to actually interact with my OData feed from the server.

I first needed to make an HTTP request

        let request = NSMutableURLRequest(url: NSURL(string: url)! as URL)
        request.httpMethod = "POST"
        request.addValue("application/json",forHTTPHeaderField: "Content-Type")
        request.addValue("application/json",forHTTPHeaderField: "Accept")
        request.httpBody = data as Data

The “url” I had to created to match my MDC instance and XSODATA service.

let url = ""

With the “url” figured out and the HTTP request in place the last remaining piece was of course defining the “data” that was going to be sent to the server which was a JSON model.

        let para:NSMutableDictionary = NSMutableDictionary()
        para.setValue(instanceOfSettings.getUserName(), forKey: "USERNAME")
        para.setValue(, forKey: "DEVICEID")
        let jsonData: NSData
            jsonData = try para, options: JSONSerialization.WritingOptions()) as NSData
            return jsonData
        } catch _ {
            print ("opps")
            return nil

Then finally I needed to make the call itself, which I did as a function.

func sendRequest(request: NSMutableURLRequest, callback: @escaping (String, String?) -> Void) {  
        let task = URLSession.shared
            .dataTask(with: request as URLRequest) {
                (data, response, error) -> Void in
                if (error != nil) {
                    callback("", error?.localizedDescription)
                } else {
                    callback(NSString(data: data!, encoding: String.Encoding.utf8.rawValue)! as String, nil)

In the end I learned quickly that I can reuse multiple pieces of this code and just adjust the JSON creation portion depending on the service I wish to post to. Perhaps this will help you as well.

Assigned Tags

      Be the first to leave a comment
      You must be Logged on to comment or reply to a post.