from this public postman mock server https://fb76208c-d403-4f0e-94fe-1b57cf284a4c.mock.pstmn.io/relays
you will receive this json reply { "relays": [ { "room": "Office", "state": "Off", "bcm": "2" }, { "room": "Garage", "state": "Off", "bcm": "3" }, { "room": "UpStairs", "state": "Off", "bcm": "4" }, { "room": "Master", "state": "Off", "bcm": "17" }, { "room": "MasterBath", "state": "Off", "bcm": "27" }, { "room": "FrontDoor", "state": "Off", "bcm": "15" }, { "room": "LargeBedroom", "state": "Off", "bcm": "18" }, { "room": "SmallBedroom", "state": "Off", "bcm": "22" }, { "room": "Kitchen", "state": "Off", "bcm": "24" }, { "room": "Playroom", "state": "Off", "bcm": "10" }, { "room": "Outside", "state": "Off", "bcm": "9" }, { "room": "Laundry", "state": "Off", "bcm": "25" }, { "room": "Hexroom", "state": "Off", "bcm": "5" }, { "room": "Empty1", "state": "Off", "bcm": "6" }, { "room": "Empty2", "state": "Off", "bcm": "13" }, { "room": "Empty3", "state": "Off", "bcm": "19" } ] }
playground code below fails to decode. what I'm I doing wrong?
struct switchState: Decodable {
let room: String
let state: String
let bcm: String
}
struct piOutput: Decodable {
let relays: switchState // set outer key relays
}
import UIKit
let url = URL(string: "https://fb76208c-d403-4f0e-94fe-1b57cf284a4c.mock.pstmn.io/relays")!
let task = URLSession.shared.dataTask(with: url) { data, response, error in
// ensure there is no error for this HTTP response
guard error == nil else {
print ("error: \(error!)")
return
}
// ensure there is data returned from this HTTP response
guard let data = data else {
print("No data")
return
}
// Parse JSON into array of Car struct using JSONDecoder
guard let relays = try? JSONDecoder().decode([piOutput].self, from: data) else {
print("Error: Couldn't decode data array")
return
}
for switches in relays {
print("switch state is \(switches.relays.room)")
print("room name is \(switches.relays.room)")
print(relays)
}
}
// execute the HTTP request
task.resume()