I’ve read through a number of other posts and replies but still can’t figure out what I’m missing.
I have
struct Station: Codable {
let code: String
let data: PlantData
}
struct PlantData: Codable {
let batteryPercent: Int
let capacity: Float
let dayEnergy: Float
}
…
func getSCPosts (completion: @escaping (PlantData) -> ()) {
Which builds the request and then performs the call with
let task = URLSession.shared.dataTask(with: request) { data, response, error in
// Handle the response data, error, etc.
if let error = error {
print("Error: (error)")
return
}
guard let data = data else {
print("No data received")
return
}
// Parse the response data
do {
let json = try JSONDecoder().decode(Station.self, from: data)
DispatchQueue.main.async {completion(json.data)}
print(json.data)
} catch {
print("Error parsing JSON: (error)")
}
}
task.resume()
If I commentent out the DispatchQueue.main.async line, the print above shows the format of the data in the console as:
PlantData(batteryPercent: 96, capacity: 5.18, dayEnergy: 0.6)
For the view, which I think is where the issue is, I have
struct SolisCloud: View {
@State var solisResults: PlantData?
var body: some View {
VStack {
Text("My Solis Energy")
.onAppear{
getSCPosts(completion: { (solisResults) in self.solisResults = solisResults })
}
}
}
}
When I print solisResults in the console I just get ‘nil’.
Following a number of posts I’ve found, and various examples from others, I have tried to work out the correct way to pass the data through but for some reason I can’t get my head around it.
I think the issue is with the way I am passing the data received back from the API through to the screen, either in how I am defining solisResults?
I’m probably missing something obvious but any help would be greatly appreciated.
Marc H is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.