-1

I am trying to pull car information from the following API. but I can't seem to display the information in my tableview... Any and all help is appreciated!

viewController

var hondaList: [HondaModel] = []
override func viewDidLoad() {
    //let jsonUrl = "https://api.myjson.com/bins/149ex5"
    let url = URL(string: "https://api.myjson.com/bins/149ex5")

    URLSession.shared.dataTask(with: url!) { (data, urlrespone , error) in
        do{
            try self.hondaList = JSONDecoder().decode([HondaModel].self, from: data!)
            for honda in self.hondaList {
                print(honda.name)
            }
            DispatchQueue.main.async {
                self.tableView.reloadData()
            }
        } catch{  
            print( "Error in fectching from https://api.myjson.com/bins/149ex5")
        }
    }.resume()
    super.viewDidLoad()

}

Model

import Foundation
struct HondaModel: Decodable {
    let name: String
    let engine: String
    let transmission: String
    let ocolor: String
    let icolor: String
    let vin: String
}
vadian
  • 274,689
  • 30
  • 353
  • 361
JFarina5
  • 23
  • 12

2 Answers2

3

This is a very common mistake: You are ignoring the root object (and both possible errors)

Add this struct

struct Root : Decodable {  
    private enum CodingKeys: String, CodingKey { case results = "Results", message = "Message" }

    let results : [HondaModel]
    let message : String
}

and decode

if let error = error { print(error); return }
do {
    let root = try JSONDecoder().decode(Root.self, from: data!)
    self.hondaList = root.results
...  

and please, please, print the error rather than a meaningless literal string. The error tells you what's wrong.

catch {
   print(error)
}

In your case you would get

"Expected to decode Array<Any> but found a dictionary instead."

which is a very significant hint.

vadian
  • 274,689
  • 30
  • 353
  • 361
  • Sorry about the error response... I'm still new to all of this. So your answer worked, but I am getting one of those dang thread errors after the console almost prints all of the car names. Here is the error: Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value – JFarina5 Mar 05 '18 at 12:13
  • I am not sure how to format this comment correctly, but this is the line where the error is: DispatchQueue.main.async { self.tableView.reloadData() } – JFarina5 Mar 05 '18 at 12:15
  • If the code crashes in the `reloadData()` line then the outlet of the table view is not connected in Interface Builder. It's not related to the decoding part. – vadian Mar 05 '18 at 12:16
  • Any idea where I would need to investigate to fix the issue? – JFarina5 Mar 05 '18 at 12:22
  • Select the storyboard in the navigation bar, select the view controller, press ⌥⌘6. Check if the table view is connected to the `tableView` outlet. If not control-drag from the view controller to the table view, select the proper outlet. – vadian Mar 05 '18 at 12:25
  • So, I made sure that all of the outlets and views were connected with no prevail, any other suggestions? – JFarina5 Mar 05 '18 at 12:39
  • Once again: *If the code crashes in the `reloadData()` line* then `tableView` is `nil` which means it's not connected. Prove it by setting a breakpoint in that line. please see https://stackoverflow.com/questions/32170456/what-does-fatal-error-unexpectedly-found-nil-while-unwrapping-an-optional-valu – vadian Mar 05 '18 at 12:42
  • Okay, does it matter that this is a view you receive after clicking a button on the initial page? – JFarina5 Mar 05 '18 at 13:23
0

try this

 if let resultJSON = data?["Results"] as? [[String: Any]] {
                                                    do {
                                                        let _data = try JSONSerialization.data(withJSONObject: resultJSON, options: .prettyPrinted)
                                                        self.hondaList = try JSONDecoder().decode([HondaModel].self, from: _data)
                                                       // … same thing
           }
 } 
SuryaKantSharma
  • 1,113
  • 12
  • 27