0

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.

user1020496
  • 99
  • 1
  • 9
  • have you run it on postman ?? are you sure you are passing right params and headers? also make sure the encoding is correct. – Keshu R. Dec 07 '19 at 10:32
  • Yes I've run it on Postman and it works. Not sure how to send a raw body as the parameter. – user1020496 Dec 07 '19 at 10:45

2 Answers2

0

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"])
Keshu R.
  • 5,045
  • 1
  • 18
  • 38
0

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.

user1020496
  • 99
  • 1
  • 9