swift 您能帮助我解决从webAPI获取数据时出错的问题吗

mm9b1k5b  于 2023-02-07  发布在  Swift
关注(0)|答案(1)|浏览(119)

我从https://fruityvice.com/api/fruit/all得到了这个API,我想得到它的名字来显示它到一个tableview,并在detailsviewcontroller上显示其余的。这是我所做的全部,但我不知道为什么数据仍然无法加载。希望有人能帮助我,谢谢。
视图控制器

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))
v8wbuo2f

v8wbuo2f1#

你的json有一些嵌套的数据。它们应该在单独的结构中,如下所示。

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()
}

相关问题