【问题标题】:Api call returning error **keyNotFound....**Api 调用返回错误 **keyNotFound....**
【发布时间】:2021-04-11 21:28:29
【问题描述】:

我正在尝试进行 api 调用,我正在查询中构建 api 并像往常一样解析它,但出现错误:

keyNotFound(CodingKeys(stringValue: "locationType", intValue: nil), Swift.DecodingError.Context(codingPath: [_JSONKey(stringValue: "Index 0", intValue: 0)], debugDescription: "没有值与键 CodingKeys(stringValue: "locationType", intValue: nil) ("locationType").", 底层错误: nil) 相关联 **)

获取数据:

func fetchData(completionHandler: @escaping ([Root]) -> Void) {
    
    let queryItems = [URLQueryItem(name: "lat", value: "51.176519"),URLQueryItem(name: "lng", value: "-0.622557"),URLQueryItem(name: "date", value: "2020-11")]
    var urlComponents = URLComponents(string: "https://data.police.uk/api/crimes-street/all-crime")
    urlComponents?.queryItems = queryItems
    guard let combinedUrl = urlComponents?.url else {return}
    print(combinedUrl)
    let task = URLSession.shared.dataTask(with: combinedUrl,completionHandler : { (data, response, error) in
        if let error = error {
            print("Error with fetching accounts: \(error)")
            return
        }
        guard let httpResponse = response as? HTTPURLResponse,
              (200...400).contains(httpResponse.statusCode) else {
            print("Error with the response , unexpected status code:\(response)")
            return
        }
        guard let data = data else {return}
        do {
            let decoder = JSONDecoder()
            let dataSummary = try decoder.decode([Root].self, from: data)
            completionHandler(dataSummary.self ?? [])
        } catch {
            print(error)
        }
    })
    task.resume()
}

视图控制器:

    override func viewDidLoad() {
    super.viewDidLoad()
    networking.fetchData{[weak self] (jsonValues) in
        self?.jsonValues = jsonValues ;print("JSON values Inside closure : \(jsonValues)")
    }
    print("JSON values outside closure: \(jsonValues)")
}

根结构:

public struct Root: Codable {
public let category, location_Type: String
public let location: Location
public let context: String
public let outcomeStatus: OutcomeStatus
public let persistentId: String
public let id: Int
public let locationSubtype, month: String
public init(category: String, locationType: String, location: Location, context: String, outcomeStatus: OutcomeStatus, persistentId: String, id: Int, locationSubtype: String, month: String) {
    self.category = category
    self.locationType = locationType
    self.location = location
    self.context = context
    self.outcomeStatus = outcomeStatus
    self.persistentId = persistentId
    self.id = id
    self.locationSubtype = locationSubtype
    self.month = month
}

}

任何帮助都会很棒!

【问题讨论】:

  • print(jsonValues)替换为print("JSON Values Outside closure: :\(jsonValues)"),将self?.jsonValues = jsonValues替换为self?.jsonValues = jsonValues; print("JSON Values Inside closure: :\(self?.jsonValues)"),看看先打印的是什么?
  • 嘿,谢谢你的评论,我已经替换了你推荐的。 '''override func viewDidLoad() { super.viewDidLoad() networking.fetchData{[weak self] (jsonValues) in self?.jsonValues = jsonValues ;print("JSON values Inside closure : (jsonValues)") }''' print("JSON values outside Closure: (jsonValues)") } 唯一打印的是闭包外的 JSON,它是空的 []
  • 现在,做一个正确的do{try}catch{} 而不是try? 并打印错误。您只是忽略了当前的错误。
  • 所以我添加了 do catch 块do { let decoder = JSONDecoder() let dataSummary = try decoder.decode([Root].self, from: data) completionHandler(dataSummary.self ?? []) } catch { print(error.localizedDescription) } 并且错误是无法读取数据,因为它丢失了。不确定是什么问题。
  • 不打印本地化描述,只打印错误。

标签: json swift xcode api swift5


【解决方案1】:

错误提示它在 API 响应中找到 nil,因为我没有考虑到响应可能是 nil 我在 Root struct optional 中设置了值,则解析成功。

public let category, location_Type: String?
public let location: Location
public let context: String
public let outcomeStatus: OutcomeStatus?
public let persistentId: String?
public let id: Int
public let locationSubtype, month: String?

【讨论】:

    猜你喜欢
    • 2017-02-10
    • 2023-03-23
    • 1970-01-01
    • 1970-01-01
    • 2013-10-01
    • 2015-10-28
    • 2023-01-26
    • 2014-08-07
    • 1970-01-01
    相关资源
    最近更新 更多