Model Class
public struct Products : Codable {
let data: [ProductData]
let error: Bool
let message: String
}
public struct ProductData : Codable {
let id, category, subCategory, name, status: String
}
ViewModel Class :
import Foundation
import Alamofire
final class GetProductsViewModel : ObservableObject {
@Published var products : [ProductData] = []
func productRequest() {
let productsurl = "https://auroraa.site/suresh-packers/admin/api/get-products.php"
AF.request(productsurl, method: .post,
parameters: ["type": "get_products","sub_category": "2"],
encoding: URLEncoding.default,
headers: nil,
interceptor: nil).response { responce in
switch responce.result {
case .success(let data):
do {
let jsonData = try JSONDecoder().decode(Products.self, from: data!)
print("Product Names : ",jsonData)
self.products = jsonData.data
} catch {
print(error)
}
case .failure(let error):
print(error)
}
}
}
}
When I run the app .. Api call return the error statement of
"keyNotFound(CodingKeys(stringValue: "subCategory", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "data", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "subCategory", intValue: nil) ("subCategory").", underlyingError: nil))"
The API dose not send "subCategory" Maybe "SubCategory" is receiving. You can use CodingKey like this
public struct ProductData : Codable {
let id, category, subCategory, name, status: String
enum CodingKeys: String, CodingKey {
...
case subCategory = "SubCategory"
case category = "Category"
...
}
}