-3

I have the following implementation; however, I am getting the following error.

Thread 5: Fatal error: Unexpectedly found nil while unwrapping an Optional value

struct StoreProducts: Decodable {
  let totalProducts: Int?
  let pageNumber: Int?
}

var products: StoreProducts!

override func viewDidLoad() {
    super.viewDidLoad()

    fetchProducts(completion: { success in
        print(self.products as Any)
        self.products = products
        self.productTableView.reloadData()
    })
}

func fetchProducts(completion: @escaping ((Any) -> Void)) {
    let jsonUrlString = "https://mobile-server.com/products/1/20"
    guard let url = URL(string: jsonUrlString) else { return  }

    // Note: Swift 4 JSONCoder()
    URLSession.shared.dataTask(with: url) { (data, response, err) in
        guard let data = data else { return }
        do {
            // getting error here
            self.products = try JSONDecoder().decode(StoreProducts.self, from: data)
            //check response status 200 OK
            if pageProducts.statusCode != 200
            {
                print("Connection issue, please try again later")
            }
            else{
                completion(self.products as Any)
            }
        }
        //check error
        catch let jsonErr {
            print("Error serializing json:", jsonErr)
        }
    }.resume()
}
casillas
  • 16,351
  • 19
  • 115
  • 215

1 Answers1

2

I tried your code and not sure where you declare the pageProducts but you need to check the response variable instead and cast it to HTTPURLReponse if you want to check the statusCode of the HTTP call.

fetchProducts(completion: { success in
  if let products = success as? StoreProducts
  {
     print(products.totalProducts!)
     print(products.pageNumber!)
   }
})


func fetchProducts(completion: @escaping ((AnyObject) -> Void)) {
    let jsonUrlString = "https://mobile-tha-server.appspot.com/walmartproducts/1/20"
    guard let url = URL(string: jsonUrlString) else { return  }

    // Note: Swift 4 JSONCoder()
    URLSession.shared.dataTask(with: url)
    { (data, response, err) in
      guard let data = data else { return }
      do {
        // getting error here
        self.products = try JSONDecoder().decode(StoreProducts.self, from: data)
        //check response status 200 OK
        if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode != 200 {
          print("Connection issue, please try again later")
        }
        else{
          completion(self.products as AnyObject)
        }
      }
        //check error
      catch let jsonErr {
        print("Error serializing json:", jsonErr)
      }
      }.resume()
  }
Christian Abella
  • 5,747
  • 2
  • 30
  • 42