I’m writing a swift program and I need to use an API to get the response.
Here is the API url: http://text-processing.com/api/sentiment/
document: http://text-processing.com/docs/sentiment.html
When I test it on terminal, it works well:
//command in terminal
curl -d "text=great" http://text-processing.com/api/sentiment/
//what I got
{"probability": {"neg": 0.30135019761690551, "neutral": 0.27119050546800266, "pos": 0.69864980238309449}, "label": "pos"}
But when I want to decode the response data in Swift, it failed.
My codes are attached as following:
struct Result : Codable{
var probability: Probability
var label: String
struct Probability: Codable{
var neg: Double
var neutral: Double
var pos: Double
}
}
class ResponseData: ObservableObject{
@Published var result: [Result] = []
func API()-> Bool{
guard let url = URL(string: "http://text-processing.com/api/sentiment/") else { fatalError("Missing URL") }
var request = URLRequest(url: url)
request.setValue("text=great", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let session = URLSession.shared
let dataTask = session.dataTask(with: request as URLRequest, completionHandler: { (data, response, error) -> Void in
if (error != nil) {
print(error)
} else {
let httpResponse = response as? HTTPURLResponse
print(httpResponse)
guard let data = data else { return }
DispatchQueue.main.async {
do {
let decodedResult = try JSONDecoder().decode(Result.self, from: data)
self.result = [decodedResult]
print(self.result)
} catch let error {
print("Error decoding: ", error)
}
}
}
})
dataTask.resume()
return true
}
}
The error is:
Error decoding: dataCorrupted(Swift.DecodingError.Context(codingPath: [], debugDescription: "The given data was not valid JSON.", underlyingError: Optional(Error Domain=NSCocoaErrorDomain Code=3840 "Invalid value around line 1, column 0." UserInfo={NSDebugDescription=Invalid value around line 1, column 0., NSJSONSerializationErrorIndex=0})))
I have searched a lot but could not find an available solution. Could anyone share some idea? Thanks a lot.
2
Answers
You’re requesting invalid request.
is not correct, you have to send it as body in form-url-encoded
You need to identify where lies your issue:
So let’s print what you in fact receive:
That gives:
So your JSON Decoding files because you didn’t receive the expected output, it’s not even JSON.
Now, let’s see the working cURL Sample:
The
-d
is forhttpBody
, not as your write for headers. If that were the case, you would have-H 'Content-Type: text=great'
. Yours doesn’t make sense at all, as what means "Content-Type" parameter in requests.So, the request creation should be: