有什么方法可以让我使用变量"bggg";?我试图进行一个api调用,然后使用数据来更改视图,但我不知道如何访问变量。它说在它的范围内找不到bggg。
public struct RootView: View {
public init() {Task {
let (data, _) = try await URLSession.shared.data(from: URL(string:"https://api.openweathermap.org/data/2.5/onecall?lat=32&lon=-94&units=imperial&exclude=minutely,hourly,daily&appid=bf1daa8bf4997bc299d459c8db985f8f")!)
let decodedResponse = try JSONDecoder().decode(WeatherResponse.self, from: data)
var bggg = decodedResponse.current.weather.description
}}
var body: some View {
Text("(bggg)")
Color.red
}
}
您可以使用Combine:设置一个发布者,这意味着发送数据的属性,然后将另一个属性设置为订阅者(该属性将监听发布者(如果发生任何更改,订阅者将立即收到通知
1.设置发布者
class DownloadWithCombineViewModel: ObservableObject {
@Published var bggg: String = ""
public init() {Task {
let (data, _) = try await URLSession.shared.data(from: URL(string:"https://api.openweathermap.org/data/2.5/onecall?lat=32&lon=-94&units=imperial&exclude=minutely,hourly,daily&appid=bf1daa8bf4997bc299d459c8db985f8f")!)
let decodedResponse = try JSONDecoder().decode(WeatherResponse.self, from: data)
var bggg = decodedResponse.current.weather.description
}
}
2.设置订阅者(ObservedObject(
struct ContentView: View {
@ObservedObject var value = DownloadWithCombineViewModel()
var body: some View {
Text("(value.bggg)")
Color.red
}
}
SwiftUI视图状态由各种属性包装器管理:@State
、@StateObject
、@Binding
、@EnvironmentObject
等。这些内容将在大多数SwiftUI教程中介绍,但在这种情况下,如果您想将state保持在视图的本地,则可以像这样实现:
public struct RootView : View {
@State private var bggg: String = "Loading…"
public var body: some View {
Text("(bggg)")
.task {
do {
let (data, _) = try await URLSession.shared.data(from: URL(string:"https://api.openweathermap.org/data/2.5/onecall?lat=32&lon=-94&units=imperial&exclude=minutely,hourly,daily&appid=bf1daa8bf4997bc299d459c8db985f8f")!)
let decodedResponse = try JSONDecoder().decode(WeatherResponse.self, from: data)
self.bggg = decodedResponse.current.weather.description
} catch {
self.bggg = "Error: (error)"
}
}
}
}