我正在尝试使用API调用。每次尝试使用API调用时都出现错误。
typeMismatch(斯威夫特.数组,斯威夫特.解码错误.上下文(编码路径:[],调试描述:“应解码数组,但找到的是字典。",underlyingError:无))
这是我在控制台中模拟代码时看到。
下面是我在应用程序中尝试调用的json格式。Click
我的模型
struct Article: Codable {
let author: String
let title, articleDescription: String
let url: String
let urlToImage: String
let publishedAt: Date
let content: String?
enum CodingKeys: String, CodingKey {
case author, title
case articleDescription = "description"
case url, urlToImage, publishedAt, content
}
}
这是我的API调用函数。
import UIKit
class ViewController: UIViewController {
var article = [Article]()
override func viewDidLoad() {
super.viewDidLoad()
jsonParse {
print("success")
}
view.backgroundColor = .red
}
func jsonParse(completed: @escaping () -> ()) {
let url = URL(string: "https://newsapi.org/v2/top-headlines?country=tr&apiKey=1ea9c2d2fbe74278883a8dc0c9eb912f")
let task = URLSession.shared.dataTask(with: url!) { data, response, error in
if error != nil {
print(error?.localizedDescription as Any)
}else {
do {
let result = try JSONDecoder().decode([Article].self, from: data!)
DispatchQueue.main.async {
print(data as Any)
print("success")
self.jsonParse {
print("success")
}
}
}catch {
print(error.localizedDescription)
}
}
}
task.resume()
}
}
你能帮我解决一下我的问题吗,谢谢。
1条答案
按热度按时间zsbz8rwp1#
这是一个很常见的错误:忽略根对象,一个字典,对于
Decodable
,必须从顶部解码JSON。添加此结构
及解码了
和never
print(error.localizedDescription)
在一个可编码的catch块中。