1
let url = URL(string: "https://api.letsbuildthatapp.com/jsondecodable/courses")
    URLSession.shared.dataTask(with: url!) { (data, response, err) in
        guard let data = data else { return }
        do {
            let appData = try JSONDecoder().decode([App].self, from: data)
            print(appData)

        } catch let err {
            print("Err", err)
        }

    }.resume()

This is how I parsed the json. But I want to add those parsed data to my array to use it to populate mytableview.

struct App: Decodable {
    var id: Int
    var name: String
}

var apps = [App]()

This is what I get after printed the appData in my console.

[CustomTableView.App(id: 1, name: "Instagram Firebase"), CustomTableView.App(id: 2, name: "Podcasts Course"), CustomTableView.App(id: 3, name: "Intermediate Training Core Data"), CustomTableView.App(id: 4, name: "Kindle Basic Training")]

Can you help me to understand this concept because I'm new in iOS and searched a lot to find the answer. Thank you so much

This is my whole code

enter image description here

3
  • apps.append(contentOf: appData) just after the print(appData)? But you might want to do a tableViewreloadData() also, and do that in Main Thread.
    – Larme
    Commented Jul 16, 2018 at 12:39
  • you have to know the basics of json parsing here it is, go through this you will get clarification developer.apple.com/swift/blog/?id=37 Commented Jul 16, 2018 at 12:49
  • Thank you so much for the answer. I will search more to learn basics
    – user10088051
    Commented Jul 16, 2018 at 13:05

2 Answers 2

1

You need to do this

DispatchQueue.main.async {
    self.apps = appData
    self.tableView.reloadData()
}

OR

DispatchQueue.main.async {
    self.apps.append(contentsOf:appData)
    self.tableView.reloadData()
}
1
  • 1
    Thank you so much for your detailed answer. I solved the problem
    – user10088051
    Commented Jul 16, 2018 at 13:03
1

add :

self.apps = appData

right under print(appData)

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.