0

I have tried many ways to Parse my JSON reply but all I get is "nil"

I have this code

let url = URL(string: "https://mywebsitexxxx.com/api/v2?")!
var request = URLRequest(url: url)
request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
let postString = "key=333&quantity=44"
request.httpBody = postString.data(using: .utf8)
let task = URLSession.shared.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print("error=\(String(describing: error))")
                 return
    }

    if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
        print("statusCode should be 200, but is \(httpStatus.statusCode)")
        print("response = \(String(describing: response))")
    }
    DispatchQueue.main.async{
    let responseString = String(data: data, encoding: .utf8)
    print("responseString = \(responseString!)")
                }
}
task.resume()

The reply I get here is:

responseString = {"received":1312312}

However if I try to ParseJson, example by adding this to the VC:

struct apiReply: Codable {
    let errorReply: String?
    let receivedReply: String?

    private enum CodingKeys: String, CodingKey {
        case errorReply = "error"
        case receivedReply = "received"
          }
}

and this to the button function:

DispatchQueue.main.async{
  let parsedJson = try? JSONDecoder().decode(apiReply.self, from: data)
print(parsedJson)
}

all I get is "nil"

Arasuvel
  • 2,971
  • 1
  • 25
  • 40
Sasha
  • 3
  • 2

0 Answers0