【问题标题】:Cannot Access News API id in Swift无法在 Swift 中访问新闻 API id
【发布时间】:2020-06-10 16:18:20
【问题描述】:

当我尝试运行我的代码时出现此错误,因为我不知道如何访问 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()
    }
}

这里是 postData 代码:

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

【问题讨论】:

  • 您错过了source 步骤,您可以在其中找到id。这就是说的错误。如果您对 JSON 进行格式化,您会发现 idtitleurl 不在同一级别。要么为自己添加另一个结构,要么为该嵌套使用自定义 init。

标签: json swift api


【解决方案1】:

正如 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?
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-08-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多