I'm trying to decode the JSON feed of this site:
https://gbfs.urbansharing.com/edinburghcyclehire.com/station_information.json
I've created structs for the JSON feed like this:
import Foundation
// MARK: - Welcome
struct Welcome: Codable {
var lastUpdated, ttl: Int
var data: DataClass
}
// MARK: - DataClass
struct DataClass: Codable {
var stations: [Station]
}
// MARK: - Station
struct Station: Codable {
var stationID, name, address: String
var lat, lon: Double
var capacity: Int
}
and a ContentView like this:
import SwiftUI
struct ContentView: View {
@State private var stations = [Station]()
var body: some View {
NavigationView {
List(stations, id: \.name) { station in
VStack(alignment: .leading) {
Text(station.name)
.font(.title2)
Text(String(station.capacity))
}
}
.navigationBarTitle("Bike Docker", displayMode: .large)
.onAppear(perform: loadStationData)
}
}
func loadStationData() {
guard let url = URL(string: "https://gbfs.urbansharing.com/edinburghcyclehire.com/station_information.json") else {
print("Invalid URL")
return
}
let request = URLRequest(url: url)
URLSession.shared.dataTask(with: request) { data, response, error in
if let data = data {
print(data)
if let decodedResponse = try?
JSONDecoder().decode(Welcome.self, from: data) {
DispatchQueue.main.async {
let welcome = decodedResponse
self.stations = welcome.data.stations
}
return
}
}
print("Fetch failed: \(error?.localizedDescription ?? "Unknown error.")")
}.resume()
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
This always triggers the fatal error and never decodes = not sure what I am doing wrong.. would be immensely greatful for any help