infernouk infernouk - 24 days ago 7
JSON Question

JSON downloading but not adding to UITable, but no errors?

I have an API that loads into my app:


https://wger.de/api/v2/exercise/?language=2


I have no errors on the API call and no errors in the table view where I run the get data function. Its worked previously perfectly until now. I havent changed any code.

I assumed the servers would be down for the call, but they arent as you can see.

I am running a print 'request was successful' which is displayed in the debug when running, so its getting the data, however the print(self.exercises) returns an empty array hence no table data...any ideas? Here is the API call

open class ApiService: NSObject {

open func getData(completionHandler: @escaping (NSDictionary?, NSError?) -> Void) -> Self {

//loads api filtering by english only
let requestUrl = "https://wger.de/api/v2/exercise/?format=json&language=2"

Alamofire.request(requestUrl, method: .get, encoding: URLEncoding.default)
.responseJSON { response in
switch response.result {
case .success( let data):
print("Request was sucessful")
completionHandler(data as? NSDictionary, nil)

case .failure(let error):
print("Request failed with error: \(error)")
completionHandler(nil, error as NSError?)
}
}
return self
}


Table Function

func getApiData() {

let _ = apiService.getData() {
(data, error) in
if let data = data {
if let results = data["results"] as? [[String:Any]] {
for result in results {
if let exercise = Exercise(dictionary: result) {
self.exercises.append(exercise)
}
}
self.exercisesTableView.reloadData()
print(self.exercises)
}
}
}
}


I am also using a serialization model if that could interfere?

final public class Exercise {
var id: Int
var descrip: String
var name: String
var language: [Int]
var muscles: [Int]
var musclesSecondary: [Int]
var equipment: [Int]

public init?(dictionary: [String: Any]) {

guard
let id = dictionary["id"] as? Int,
let descrip = dictionary["description"] as? String,
let name = dictionary["name"] as? String,
let language = dictionary["language"] as? [Int],
let muscles = dictionary["muscles"] as? [Int],
let musclesSecondary = dictionary["muscles_secondary"] as? [Int],
let equipment = dictionary["equipment"] as? [Int]
else { return nil }

self.id = id
self.descrip = descrip
self.name = name
self.language = language
self.muscles = muscles
self.musclesSecondary = musclesSecondary
self.equipment = equipment
}

Answer

Sorry,

I havent changed any code

is wrong.

You added the properties musclesSecondary and language and exactly there is the error: language is single Int rather than an array.

var language: Int
...
let language = dictionary["language"] as? Int,