Posting API request to Openhab2 and Swift

103 Views Asked by At

I am trying to post a request to my Openhab system from a custom Swift iOS application I am developing however I can't seem to get a response.

I'm using the below but can't get the sensor to trigger.

AF.request("http://192.168.1.1:8080/rest/items/BinarySensor", method: .post, parameters: ["":"ON"], encoding: URLEncoding.httpBody, headers: ["Content-Type":"text/plain"])

Any help appreciated.

2

There are 2 best solutions below

2
Keshu R. On BEST ANSWER

You need to change your encoding to JSONEncoding.default and your headers to application/json. Here is how your request would look like now

AF.request("http://192.168.1.1:8080/rest/items/BinarySensor", method: .post, parameters: ["":"ON"], encoding: JSONEncoding.default, headers: ["Content-Type":"application/json"])
0
user1020496 On

I've gone down a different path. Not using Alamofire and just using the standard Swift networking. Postman allows the creation of multiple different language code blocks for a particular request so using the request it generates.

If anyone wants to know how to do it without Alamofire the answer is below.

import Foundation

var semaphore = DispatchSemaphore (value: 0)

let parameters = "OFF"
let postData = parameters.data(using: .utf8)

var request = URLRequest(url: URL(string:"http://192.168.x.x:8080/rest/items/BinarySensor")!,timeoutInterval: Double.infinity)
request.addValue("text/plain", forHTTPHeaderField: "Content-Type")

request.httpMethod = "POST"
request.httpBody = postData

let task = URLSession.shared.dataTask(with: request) { data, response, error in 
  guard let data = data else {
    return
  }
  semaphore.signal()
}

task.resume()
semaphore.wait()

I'm sure there is a better way but this way works.