我尝试过您的代码,但不确定您在哪里声明pageproducts,但如果您想检查HTTP调用的状态代码,则需要检查响应变量并将其强制转换为httpurlreponse。
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()
}