[ad_1]
I’m creating a brand new model of an current app and need to use the brand new async await
format for an internet request. Putting a break on the JSONDecoder().decode line I see that I do have information –
however the decoding doesn’t work. (The url and my key DO work within the previous model)
This is the JSON format of the online supply (shortened – there are numerous extra objects in
a fuel_station):
{
"station_locator_url":"https://afdc.vitality.gov/stations/",
"total_results":110,
"station_counts":{},
"fuel_stations":[
{
"access_code":"public",
"access_days_time":"24 hours daily; call 866-809-4869 for Clean Energy card",
"access_detail_code":"KEY_ALWAYS",
"cards_accepted":"CleanEnergy",
"date_last_confirmed":"2021-09-10",
}
]
}
I created the next fashions from the above:
enum CodingKeys: String, CodingKey {
case fuelStations = "fuel_stations"
case accessCode = "access_code"
case accessDaysTime = "access_days_time"
case accessDetailCode = "access_detail_code"
case cardsAccepted = "cards_accepted"
case dateLastConfirmed = "date_last_confirmed"
}
struct TopLevel: Codable {
let fuelStations: [FuelStation]
}
struct FuelStation: Codable {
let accessCode, accessDaysTime, accessDetailCode, cardsAccepted: String
let dateLastConfirmed: String
let id: String
}
I put a simplified model of the preliminary view in a single file for testing:
struct SiteListView: View {
@State non-public var fuelStations: [FuelStation] = []
@State non-public var topLevel: TopLevel = TopLevel(fuelStations: [])
var physique: some View {
NavigationView {
VStack {
Checklist(fuelStations, id: .id) { merchandise in
VStack {
Textual content(merchandise.accessCode)
Textual content(merchandise.accessDaysTime)
}
}
}
.navigationTitle("Web site Checklist View")
.activity {
await loadData()
}
}//nav
}
func loadData() async {
//I imagine the DEMO_KEY within the url will permit restricted retrievals
guard let url = URL(string: "https://developer.nrel.gov/api/alt-fuel-stations/v1.json?api_key=DEMO_KEY") else {
print("Invalid URL")
return
}
do {
let (information, response) = attempt await URLSession.shared.information(from: url)
guard (response as? HTTPURLResponse)?.statusCode == 200 else { return }
print("response standing code is 200")
if let decodedResponse = attempt? JSONDecoder().decode(TopLevel.self, from: information) {
topLevel = decodedResponse
print("in decoding: topLevel.fuelStations.depend is (topLevel.fuelStations.depend)")
//I might iterate via topLevel right here and add to the fuelStations
//array however I by no means get right here
}
} catch {
print("Invalid Information")
}
}//load information
}//struct
Any steerage could be appreciated. Xcode 13.2.1 iOS 15.2
[ad_2]
