the response is coming back nil
It is not clear how have you checked that.
but even putting a breaking point in there, the code is never reached.
API requests can fail with various reasons, in some cases, the error parameter is not nil.
Please try this code and tell us what you get:
(Please show your code well-formatted.)
func getProductById(productId: Int, completion: @escaping (ProductModel) -> ()) {
let url = URL(string: "https://mysite/api/products/82")!
var request = URLRequest(url: url)
request.httpMethod = "GET"
//When you use `GET`, putting a `Content-Type` header does not make sense, usually...
//request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")
URLSession.shared.dataTask(with: request) { (data, response, error) in
if let error = error {
print("error: \(error)")
return
}
guard let data = data else {
print("data is nil")
return
}
if let response = response {
print("response: \(response)")
}
let responseText = String(data: data, encoding: .utf8) ?? "Unknown encoding"
print("responseText: \(responseText)")
do {
//I recommend you never use `try!`
let product = try JSONDecoder().decode(ProductModel.self, from: data)
DispatchQueue.main.async {
completion(product)
}
}
catch {
print(error)
}
}
.resume()
}
By the way, you have not responded to the answers and comments properly. Good interaction will help you get better solutions sooner.