我正在尝试在Xcode 9.2,Swift 4中构建一个iOS应用程序,该应用程序使用集合视图单元格来显示JSON文件中的每个类别。我正在以本教程为例 - https://www.youtube.com/watch?v=hPJaQ2Fh7Ao,但我收到一个错误:
typeMismatch(Swift.Array,Swift.DecodingError.Context(codingPath: [], debugDescription: "预期解码 Array,但找到了一个字典。
我已经尝试了几种不同的东西,但我被困住了(而且是新手(。任何关于我错过或做错什么的建议都会很棒。谢谢!
JSON API:
{
"category": [
{
"id": 216,
"title": "Spring"
},
{
"id": 219,
"title": "Earth Day"
},
{
"id": 114,
"title": "Admin. Professionals' Day"
}
]
}
视图控制器.swift:
import UIKit
struct Category: Codable {
let category: [CategoryItem]
}
struct CategoryItem: Codable {
let id: Int
let title: String
enum CodingKeys: String, CodingKey {
case id, title
}
}
class ViewController: UIViewController, UICollectionViewDataSource {
var categories = [Category]()
@IBOutlet weak var collectionView: UICollectionView!
override func viewDidLoad() {
super.viewDidLoad()
collectionView.dataSource = self
let jsonUrlString = "https://apis.*************/***/****/********"
guard let url = URL(string: jsonUrlString) else { return }
URLSession.shared.dataTask(with: url) { (data, response, err) in
guard let data = data else { return }
if err == nil {
do {
let decoder = JSONDecoder()
let ecardcategory = try decoder.decode([Category].self, from: data)
self.categories = ecardcategory
} catch let err {
print("Err", err)
}
DispatchQueue.main.async {
//print(self.categories.count)
self.collectionView.reloadData()
}
}
}.resume()
}
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
return categories.count
}
func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "customCell", for: indexPath) as? CustomCollectionViewCell
//cell?.nameLbl.text = categories[indexPath.row].title
return cell!
}
}
错误
"本以为要解码数组,却找到了字典。">
非常清楚:根对象是一个字典(用{}
表示(,所以去掉括号。
let ecardcategory = try decoder.decode(Category.self, from: data)
您必须声明数据源数组
var categories = [CategoryItem]()
并填充它
self.categories = ecardcategory.category