无法在 Swift 中访问新闻 API ID



当我尝试运行代码时出现此错误,因为我无法弄清楚如何访问 json 文件的 id。

当我运行代码时,出现此错误:

keyNotFound(CodingKeys(stringValue: "id", intValue: nil), Swift.DecodingError.Context(codingPath: [CodingKeys(stringValue: "articles", intValue: nil), _JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "No value associated with key CodingKeys(stringValue: "id", intValue: nil) ("id").", underlyingError: nil))

这是我从 API 检索数据的代码

func fetchData() {
if let url = URL(string: "https://newsapi.org/v2/top-headlines?country=gb&category=science&apiKey=7806d7a294994cd2af9d272bbfe4f334") {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error == nil {
let decoder = JSONDecoder()
if let safeData = data {
do {
let results = try decoder.decode(Results.self, from: safeData)
// Update must happen on the main thread, not in the background
DispatchQueue.main.async {
self.posts = results.articles
}
} catch {
print(error.localizedDescription)
}
}
}
}
task.resume()
}
}

这是后数据代码:

struct Results: Decodable {
let articles: [Post]
}
struct Post: Decodable, Identifiable {
var id: String
let title: String
let url: String
}

最后,这是我的代码,它应该在屏幕上呈现数据:

struct ContentView: View {
@ObservedObject var networkManager = NetworkManager()
var body: some View {
NavigationView {
// for every single post in the post array
List(networkManager.posts) { post in
Text(post.title)
}
.navigationBarTitle("Science Bite")
}
// This calls fetch data
.onAppear {
self.networkManager.fetchData()
}
}
}

正如 Larme 所说,您正在尝试从article中解码id,但它实际上存在于source字典中。将Article模型修改为以下内容以解决此问题:

struct Article: Codable {
let title, url: String
let source: Source
var id: String? {
source.id
}
}
struct Source: Codable {
let id: String?
}

最新更新