I am trying to write a function in swift that gets data from an URL JSON, and allocate it to variables in swift.
This is the function:
func getBikeData(){
guard let url = URL(string: "https://api.citybik.es//v2/networks/baksi-bisim") else {return}
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let dataResponse = data,
error == nil else {
print(error?.localizedDescription ?? "Response Error")
return }
do{
//here dataResponse received from a network request
let jsonResponse = try JSONSerialization.jsonObject(with:
dataResponse, options: [])
print(jsonResponse) //Response result
do {
//here dataResponse received from a network request
let decoder = JSONDecoder()
//Decode JSON Response Data
let model = try decoder.decode(Station.self,
from: dataResponse)
print(model.freeBikes) //Output - 1221
} catch let parsingError {
print("Error", parsingError)
}
} catch let parsingError {
print("Error", parsingError)
}
}
task.resume()
}
This is the struct's that I added, with the data I need:
// MARK: - Station
struct Station: Codable {
let emptySlots: Int
let extra: Extra
let freeBikes: Int
let id: String
let latitude, longitude: Double
let name, timestamp: String
enum CodingKeys: String, CodingKey {
case emptySlots
case extra
case freeBikes
case id, latitude, longitude, name, timestamp
}
}
// MARK: - Extra
struct Extra: Codable {
let slots: Int
let status: Status
let uid: String
}
enum Status: String, Codable {
case active = "Active"
}
This is the error I have been receiving:
Error keyNotFound(CodingKeys(stringValue: "emptySlots", intValue: nil), Swift.DecodingError.Context(codingPath: [], debugDescription: "No value associated with key CodingKeys(stringValue: \"emptySlots\", intValue: nil) (\"emptySlots\").", underlyingError: nil))
This is the first time I was working with a JSON file, and maybe I am missing something very simple. Please help.
Stationstruct. Creating a coding keys enum in which the raw values of all of the cases are the same as the case names is redundant.Stationstruct.