Yannick Fitch
Yannick Fitch

Reputation: 29

Tableview with JSON Data in Swift 4.2

I'm new to Swift and I am at my wit's end, so please be kind to me.

I am building an app which downloads data from an url by posting a specific ID and getting back an JSON array. The JSON looks like this:

[{"group":"500","from":"2019-01-01","to":"2019-01-05"},{...}]

It has the group number as "group" and a start Date "from" and an end date "to".

I want to let the different groups shown in a Tableview with the From and To-Dates as well. I managed to download the data correctly but I failed by showing them in a tableview.

My code is down below. Maybe someone of you can find out what I've done wrong.

When I run the project I get an empty table.

    import UIKit

   typealias Fahrten = [FahrtenElement]

struct FahrtenElement: Codable {
    let group: String?
    let from: String?
    let to: String?

    enum CodingKeys: String, CodingKey {
        case group = "group"
        case from = "from"
        case to = "to"
    }
}

    class BookingsController: UITableViewController {

        var tableview: UITableView!
        var groups = [Fahrten]()


        // MARK: - Table view data source

        override func viewDidLoad() {
            super.viewDidLoad()
            downloadData()
        }

        override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
            let label = UILabel()
            label.text = "Groups"
            label.backgroundColor = .yellow

            return label
        }


        // Section
        override func numberOfSections(in tableView: UITableView) -> Int {
            return 1
        }

        override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
            return self.groups.count
        }

        override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
            let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath)
            //lblname to set the title from response
            cell.textLabel?.text = "Group \(String(describing: groups[indexPath.row].group))"
            cell.detailTextLabel?.text = "From \(String(describing: groups[indexPath.row].from)) to \(String(describing: groups[indexPath.row].to))"
            return cell
        }

        func downloadData() {
            let id = "..."

            let url = URL(string: "...")!

            // request url
            var request = URLRequest(url: url)

            // method to pass data POST - cause it is secured
            request.httpMethod = "POST"

            // body gonna be appended to url
            let body = "id=(\(id))"

            // append body to our request that gonna be sent
            request.httpBody = body.data(using: .utf8)

            URLSession.shared.dataTask(with: request) { (data, response, err) in



guard let data = data else { return }


            do {

               let groups = try JSONDecoder().decode(Fahrten.self, from: data)

                print(groups)                        
self.tableview.reloadData() // I get an crash here: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value                    }
                } catch let jsonErr {
                    print("Error serializing json:", jsonErr)
                }

                }.resume()
        }

Upvotes: 0

Views: 634

Answers (2)

dahiya_boy
dahiya_boy

Reputation: 9503

Try this code.

Your model.

typealias Fahrten = [FahrtenElement]

struct FahrtenElement: Codable {
    let group: String
    let from: String
    let to: String

    enum CodingKeys: String, CodingKey {
        case group = "group"
        case from = "from"
        case to = "to"
    }
}

Use it, I am using it with local json with same structure.

func getFehData(){
    let url = Bundle.main.url(forResource: "fah", withExtension: "json")!
    do {
        let jsonData = try Data(contentsOf: url)
        let fahrten = try? JSONDecoder().decode(Fahrten.self, from: jsonData)

        print(fahrten)
    }
    catch {
        print(error)
    }
}

Output : (Dummy data)

enter image description here

Upvotes: 0

Scriptable
Scriptable

Reputation: 19750

From what I can see it looks like you are emptying the array and not reloading the data.

You should assign the resulting groups property to self.groups and then reload the data.

DispatchQueue.main.async {
    self.groups = groups // change here
    self.tableview.reloadData()
}

Upvotes: 2

Related Questions