Ошибка разделения JSON ответа по строкам табличного представления в Swift - PullRequest
0 голосов
/ 10 февраля 2020

В настоящее время у меня есть следующий массив JSON:

[
    {
        "Time": "8:10 PM",
        "Person": "Jeff",
        "Place": "London"
    }
]

Я бы разделил значения Time, Person и Place для каждого из них на отдельные ячейки.

В настоящее время у меня есть следующее:

private func fetchJSON() {

    guard let url = URL(string: "\(URLValue)lookup.php"),
        let value = value.addingPercentEncoding(withAllowedCharacters: .urlQueryValueAllowed)
        else { return }

    var request = URLRequest(url: url)
    request.httpMethod = "POST"
    request.httpBody = "value=\(value)".data(using: .utf8)

    URLSession.shared.dataTask(with: request) { data, _, error in
        guard let data = data else { return }


        do {

            self.structure = try JSONDecoder().decode([LookupStructure].self,from:data)
            DispatchQueue.main.async {

                self.tableView.reloadData()

            }
        }
        catch {
            print(error)
        }

        }.resume()

}

С LookupStructure следующее:

struct LookupStructure: Decodable {

    let Time: String
    let Person: String
    let Place: String


    enum CodingKeys : String, CodingKey {
        case Time, Person, Place
    }

}

У меня просто проблемы с пониманием, как я могу отобразить это JSON данные по каждой строке, что означает

Time is on row 0, Person is on row 1 and Place is on row 2

1 Ответ

0 голосов
/ 10 февраля 2020

Примерно так должно работать:

class MyViewController: UIViewController, UITableViewDataSource {

    func numberOfSections(in tableView: UITableView) -> Int {
        return self.structure.count
    }

    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 3
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        // assuming you set up your kCellIdentifier somewhere
        let cell = tableView.dequeueReusableCell(withIdentifier: kCellIdentifier) ?? UITableViewCell()

        let `struct` = self.structure[indexPath.section]
        var textLabel: String? = nil

        switch indexPath.row {
        case 0:
            textLabel = `struct`.Time
            break
        case 1:
            textLabel = `struct`.Person
            break
        case 2:
            textLabel = `struct`.Place
            break
        default:
            fatalError("oopsies")
        }

        cell.textLabel?.text = textLabel

        return cell
    }
}
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...