Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
391 views
in Technique[技术] by (71.8m points)

json - Api call returning error **keyNotFound....**

I am trying to make api call , I am building api in query and parsing it as usual , but I am getting error :

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

Fetch data :

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

ViewController :

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

Root struct :

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
}

}

Any help would be amazing!


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The error was suggesting that it found nil in API response , as I did not took for account that the response can be nil I had made values in Root struct optional,then it successfully parsed.

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?

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...