Home > OS >  Can you help me with error fetching data from webAPI
Can you help me with error fetching data from webAPI

Time:02-04

I got this api from https://fruityvice.com/api/fruit/all and i want to get the name to show it to a tableview and show the rest on a detailsviewcontroller. This is all i have done, but i don't know why the data still won't load up. Hope someone can help me, thanks.

viewcontroller

class HomeViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    @IBOutlet weak var fruitTable: UITableView!
    var fruits = [FruitData]()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        let tapGesture = UITapGestureRecognizer(target: view, action: #selector(UIView.endEditing))
         view.addGestureRecognizer(tapGesture)
        tapGesture.cancelsTouchesInView = false
        
        fetchApi{
            self.tableView.reloadData()
        }
        fruitTable.delegate = self
        fruitTable.dataSource = self
    }
    func fetchApi(completed: @escaping () -> ()) {
        let url = URL(string: "https://fruityvice.com/api/fruit/all")
        URLSession.shared.dataTask(with: url!) {data,response,error in
            if error == nil{
                do{
                    self.fruits = try JSONDecoder().decode([FruitData].self, from: data!)
                    DispatchQueue.main.async {
                        completed()
                    }
                }catch{
                    print("error")
                }
                
            }
        }.resume()
    }
    
}
here is the error log i got : 

error fetching data!: keyNotFound(CodingKeys(stringValue: "carbohydrates", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: \"carbohydrates\", intValue: nil) (\"carbohydrates\").", underlyingError: nil))

CodePudding user response:

You json has some nested data. They should be in separate struct as follows.

struct FruitData : Codable{
    let genus, name: String
    let id: Int
    let family, order: String
    let nutritions: Nutritions
}

struct Nutritions : Codable{
    let carbohydrates : Double
    let protein : Double
    let fat : Double
    let calories: Int
    let sugar: Double
}

var fruits : [FruitData] = []
func getData(completed: @escaping () -> ()) {
    let url = URL(string: "https://fruityvice.com/api/fruit/all")
    URLSession.shared.dataTask(with: url!) {data,response,error in
        if error == nil{
            do{
                fruits = try JSONDecoder().decode([FruitData].self, from: data!)
                DispatchQueue.main.async {
                    completed()
                }
            }catch{
                print(error)
            }
            
        }
    }.resume()
}
  • Related