I am getting JSON data from an api and I am not able to populate it to the tableview.
API Response
{
"inspection_data": [{
"inspection_dt_card": "February 02, 12:17AM",
"part_type_card": "XXYYZZ1",
"inspection_status_card": "Bad",
"defect_type_card": "EXTR",
"badge_color": "danger",
"line_id": "line-86"
},
{
"inspection_dt_card": "February 02, 12:17AM",
"part_type_card": "XXYYZZ2",
"inspection_status_card": "Excelllent",
"defect_type_card": "EXTR",
"badge_color": "danger",
"line_id": "line-99"
}
]
}
The model class is as follows
struct InspectionDataModel: Codable {
let inspectionData: [InspectionData]
enum CodingKeys: String, CodingKey {
case inspectionData = "inspection_data"
}
}
struct InspectionData: Codable {
let inspectionDtCard: String
let partTypeCard: String
let inspectionStatusCard: String
let defectTypeCard: String
let badgeColor: String
let lineID: String
enum CodingKeys: String, CodingKey {
case inspectionDtCard = "inspection_dt_card"
case partTypeCard = "part_type_card"
case inspectionStatusCard = "inspection_status_card"
case defectTypeCard = "defect_type_card"
case badgeColor = "badge_color"
case lineID = "line_id"
}
}
My api call is as follows
AF.request(webURL,
method: .get,
parameters: params,
encoding: URLEncoding.default,
headers: headers).responseDecodable(of: InspectionDataModel.self) { response in
switch response.result{
case .success(_):
debugPrint(response.result)
do {
let decoderResponse = try JSONDecoder().decode(InspectionDataModel.self, from: response.data!)
print(decoderResponse)
} catch { print(error) }
break
case .failure(_):
debugPrint(response.data as Any)
debugPrint(response.debugDescription)
print("Failed")
}
}
Debug Print Output
InspectionDataModel(inspectionData: [Worker_App.InspectionData(inspectionDtCard: "February 07, 01:48PM", partTypeCard: "XXYYZZ1", inspectionStatusCard: "Bad", defectTypeCard: "EXTR", badgeColor: "danger", lineID: "line-86"), Worker_App.InspectionData(inspectionDtCard: "February 07, 01:48PM", partTypeCard: "XXYYZZ1", inspectionStatusCard: "Excelllent", defectTypeCard: "EXTR", badgeColor: "danger", lineID: "line-99")])
I am not able to parse the response and populate it on the table.
Can someone help me with this issue? Thanks in advance
2
Answers
You ignore the actual – already decoded – result, the associated value in the
success
case. And also the real error in thefailure
case.It’s much simpler
decoderResponse
contains the decodedInspectionDataModel
structTry this Model with an array
Array.append(your model(keys and values))
And call array in table view cell like
array[indexPath.row]. inspection_dt_card