0
votes

I am getting an error while trying to download data from my API and display it in the TableViewController. The table view is empty. I dont understand what it wrong. Basically, I am getting this type of error:

2017-11-25 08:03:42.775803 ClassDesign[2243:51810] [] __nwlog_err_simulate_crash_libsystem libsystem simulate crash unavailable "libsystem_network.dylib: nw_host_stats_add_src :: received error for SRC_ADDED: [22] Invalid argument" 2017-11-25 08:03:42.776596 ClassDesign[2243:51810] [] nw_host_stats_add_src received error for SRC_ADDED: [22] Invalid argument, dumping backtrace: [x86_64] libnetcore-856.30.16 0 libsystem_network.dylib 0x0000000109060666 __nw_create_backtrace_string + 123 1 libsystem_network.dylib 0x00000001090772f6 nw_get_host_stats + 1083 2 libnetwork.dylib 0x0000000109356e9f nw_endpoint_resolver_start_next_child + 1382 3 libdispatch.dylib 0x0000000108ddd978 _dispatch_call_block_and_release + 12 4 libdispatch.dylib 0x0000000108e070cd _dispatch_client_callout + 8 5 libdispatch.dylib 0x0000000108de4e17 _dispatch_queue_serial_drain + 236 6 libdispatch.dylib 0x0000000108de5b4b _dispatch_queue_invoke + 1073 7 libdispatch.dylib 0x0000000108de8385 _dispatch_root_queue_drain + 720 8 libdispatch.dylib 0x0000000108de8059 _dispatch_worker_thread3 + 123 9 libsystem_pthread.dylib 0x00000001091ba1ca _pthread_wqthread + 1387 10 libsystem_pthread.dylib 0x00000001091b9c4d start_wqthread + 13 Message from debugger: Terminated due to signal 15

My code for TableViewController is:

import UIKit

class ExerciseTableViewController: UITableViewController {

var fetchedExercise = [Exercise]()

override func viewDidLoad() {
    super.viewDidLoad()

    parseData()
}

func parseData() {

    fetchedExercise = []

    let url = "https://wger.de/api/v2/exercise/?format=json&language=2&status=2"
    var request = URLRequest(url: URL(string: url)!)
    request.httpMethod = "GET"

    let configuration = URLSessionConfiguration.default
    let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)

    let task = session.dataTask(with: request) { (data, response, error) in

        if error != nil {
            print("Error while parsing JSON")
        }
        else {

            do {
                if let data = data,
                    let fetchedData = try JSONSerialization.jsonObject(with: data, options: .mutableLeaves) as? [String:Any],
                    let exercises = fetchedData["results"] as? [[String: Any]] {

                    for eachExercise in exercises
                    {
                        let name = eachExercise["name"] as! String
                        let description = eachExercise["description"] as! String

                        self.fetchedExercise.append(Exercise(name: name, description: description))

                    }
                    // print(self.fetchedExercise[3].name)
                }
            }
            catch {
                print("Error while parsing data.")
            }
        }
    }
    task.resume()
}


override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}


// MARK: - Table view data source

override func numberOfSections(in tableView: UITableView) -> Int {
    // #warning Incomplete implementation, return the number of sections
    return 1
}

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    // #warning Incomplete implementation, return the number of rows
    return fetchedExercise.count
}


override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    if let cell = tableView.dequeueReusableCell(withIdentifier: "ExerciseCell", for: indexPath) as? ExerciseCell {

        let exercise = fetchedExercise[indexPath.row]
        cell.configureCell(exercise: exercise)

        return cell

    } else {

        return UITableViewCell()
    }


}

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

}

}

Also the code for 'configureCell' function inside my custom cell class is as follows:

import UIKit

class ExerciseCell: UITableViewCell {

@IBOutlet weak var nameLbl: UILabel!

var exercise: Exercise!

func configureCell(exercise: Exercise) {

    self.exercise = exercise
    nameLbl.text = self.exercise.name
}

}
1
Where are you reloading tableview data after fetching response?Puneet Sharma

1 Answers

0
votes

At the end of the completion handler you have to reload the table view on the main thread.

Replace the line which is commented out

// print(self.fetchedExercise[3].name)

with

DispatchQueue.main.async {
    self.tableView.reloadData()
}

And you don't need neither an URL request for a default GET request nor a specific session in this case, because you don't use the delegate pattern.

However this is not related to the issue.

Replace

let url = "https://wger.de/api/v2/exercise/?format=json&language=2&status=2"
var request = URLRequest(url: URL(string: url)!)
request.httpMethod = "GET"

let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) { (data, response, error) in ...

with

let urlString = "https://wger.de/api/v2/exercise/?format=json&language=2&status=2"
let url = URL(string: urlString)!    
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in ...

And finally – as always – all .mutable... options in jsonObject(with are nonsense in Swift. Omit the parameter.