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 = "https://codejamd045495.hanatrial.ondemand.com/codejam/services/user.xsodata/entry"

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(UIDevice.current.name, forKey: "DEVICEID")
        let jsonData: NSData
        do{
            jsonData = try JSONSerialization.data(withJSONObject: 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)
                }
        }
        task.resume()
}

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.

To report this post you need to login first.

Be the first to leave a comment

You must be Logged on to comment or reply to a post.

Leave a Reply