API Error

I have this API call in my application. For some reason, the response is coming back nil. If I try the right URL, a JSON will be returned and all the nodes filled out.

So I'm trying to get the error inside the if let error = error { but even putting a breaking point in there, the code is never reached.

What am I doing wrong ?

Thanks

func getProductById(productId: Int, completion: @escaping (ProductModel) -> ()) {
    guard let url = URL(string: "https://mysite/api/products/82") else { return }    var request = URLRequest(url: url)
    request.httpMethod = "GET"
    request.setValue("application/json; charset=UTF-8", forHTTPHeaderField: "Content-Type")    URLSession.shared.dataTask(with: request) { (data, request, error) in
      if let data = data {
        print("data")      }      if let error = error {
        print("error")      }
      guard let data = data else { return }      do {
        let product = try! JSONDecoder().decode(ProductModel.self, from: data)
        DispatchQueue.main.async {
          completion(product)
        }
      }      catch {
        print(error)
      }    }
    .resume()



Answered by OOPer in 685079022

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.

Accepted Answer

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.

Fatal error: Unexpectedly found nil while unwrapping an Optional value. It happens on my View (myStore.product!.title)

API Error
 
 
Q