'How to use async values from an actor in a Text View in swiftui
I am using xcode 13.3 beta 3 and trying to modify my app to use actors. Since all of my variables are now in an actor(s) so they cannot be accessed directly, how do I use these async values in a Text View? I found one possible solution from the last post for the following link: How can I use async/await with SwiftUI in Swift 5.5?. This was the only way I could find to use an async value in a Text View. The problem with this approach is that by using @State variable, I am required to pass those values in....which I can't do...Any ideas?
struct Forecast: View {
@EnvironmentObject var ws: Webservice
@State var forecast1tempMin = 0
....
VStack {
Text("\(forecast1tempMin)")
.foregroundColor(.white)
.task {
forecast1tempMin = await ws.forecastActor.getForecast1TempMin()
}
actor Forecast_Actor {
@Published var forecast1_tempmin = 0
func setForecast1TempMin(val: Int) async {
forecast1_tempmin = val
}
func getForecast1TempMin() async -> Int {
return forecast1_tempmin
}
struct ContentView: View {
@State var text = "Loading"
// Async function
func asyncGetText() async -> String {
try? await Task.sleep(nanoseconds: 3 * NSEC_PER_SEC)
return "My text"
}
var body: some View {
Text(text)
.task {
text = await asyncGetText()
}
}
}
struct ContentView_Previews: PreviewProvider {
static var previews: some View {
ContentView()
}
}
Solution 1:[1]
The original example of how to do this came from @malhal here on stackoverflow. I changed things around a bit to suit my needs. The original issue was how to pass into a swiftui Text() view an async value from an async call. I was trying to pass in an Int and needed to make it a String.
The following solved my problem. Thanks!
@State var forecast1tempMin: String
....
var body: some View {
Text(forecast1tempMin)
.foregroundColor(.white)
.task {
forecast1tempMin = String(await ws.forecastActor.getForecast1TempMin())
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Tim |
