I'm trying to convert a curl command in order to use it within swift for an ios app i'm making. I'm using a playground project to try out this feature.
The curl command is as follows:
curl -L -X POST 'https://myurl.com/mydata' \-H 'x-api-key: xxx' \-H 'Content-Type: application/json' \-d '{"uniqueNumber": “F4”}’
When I enter this into terminal, my data is displayed.
I have browsed through stackoverflow and managed to find articles like this and this
I'm still fairly new to swift and from what I understand, curl does not work in swift and so you have to convert it to a URLRequest.
I have attempted this with my code below but keep getting a message that says "Missing Authentication Token". What am I doing wrong?
import PlaygroundSupport
import Foundation
let key = "xxx"
let url = URL(string: "https://myurl.com/mydata")
let contentType = "application/json"
let uniqueNumber = "F4"
var request = URLRequest(url: url!)
request.addValue("x-api-key: \(key)", forHTTPHeaderField: "-H")
request.addValue("Content-Type: \(contentType)", forHTTPHeaderField: "-H")
request.addValue("uniqueNumber: \(uniqueNumber)", forHTTPHeaderField: "-d")
let task = URLSession.shared.dataTask(with: request) { data, response, error in
guard error == nil else {
print(error!)
return
}
guard let data = data else {
print("Data is empty")
return
}
let json = try! JSONSerialization.jsonObject(with: data, options: [])
print(json)
}
task.resume()
PlaygroundPage.current.needsIndefiniteExecution = true
- update -
Found the issue. I had to include the requestHTTP method, as well as the httpBody. After doing this it was fully working. See below for the working code:
import PlaygroundSupport
import Foundation
let key = "xxx"
let url = URL(string: "https://myurl.com/mydata")
let contentType = "application/json"
//setting and converting the uniqueNumber (input) to a data item so it can be recognized by the API
var uniqueNumber: Data? = "{\"uniqueNumber\": \"F09\"}".data(using: .utf8) // non-nil
var request = URLRequest(url: url!)
request.httpMethod = "POST"
request.addValue(key, forHTTPHeaderField: "x-api-key")
request.addValue(contentType, forHTTPHeaderField: "Content-Type")
request.httpBody = uniqueNumber
URLSession.shared.dataTask(with: request) { (data, response, error) in
guard error == nil else { print(error!.localizedDescription); return }
guard let data = data else { print("Empty data"); return }
if let str = String(data: data, encoding: .utf8) {
print(str)
}
}.resume()
PlaygroundPage.current.needsIndefiniteExecution = true