【发布时间】:2022-11-15 13:23:12
【问题描述】:
我试图进行天气 api 调用,api 调用需要有一个位置。我传递它的位置是一个变量。但是现在我想用我在上面写的 TextField 所具有的值来更改位置值。为了安全起见,我将 apiKey 缩短了。还有更多代码,但不相关。 我只需要知道如何使用 cityTextField 结构上的 TextField 更改 WeatherClass 上的城市变量。
谢谢。
class WeatherClass: ObservableObject {
@Published var weatherAddress: String = ""
@Published var weatherDays: [WeatherDays] = []
var city: String = ""
func fetch() {
let location = city
let apiKey = "AP8LUYMSTHZ"
let url = URL(string: "https://weather.visualcrossing.com/VisualCrossingWebServices/rest/services/timeline/\(location)?key=\(apiKey)")!
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
if let weather = try? JSONDecoder().decode(WeatherData.self, from: data) {
DispatchQueue.main.async {
self.weatherAddress = weather.resolvedAddress
self.weatherDays = weather.days
}
} else {
print("City?")
}
}.resume()
}//----------------------------------- End of fetch()
}
struct WeatherData: Decodable {
let resolvedAddress: String
let days: [WeatherDays]
}
struct WeatherDays: Hashable, Decodable {
let datetime: String
let tempmax: Double
let tempmin: Double
let description: String
}
struct cityTextField: View {
@State var city: String = ""
var body: some View {
TextField("Search city", text: $city).frame(height:30).multilineTextAlignment(.center).background().cornerRadius(25).padding(.horizontal)
}
}
我已经看过很多类似的教程,但没有一个对我有真正的帮助。
【问题讨论】:
-
您是否尝试过在
WeatherClass中的city变量上使用@Published,而不是将其绑定到视图中的@State 变量? -
@synapticloop 我还没有,这里已经很晚了所以我明天要试试。无论如何感谢您的评论。我不知道这是否是回复您评论的正确方式,因为我是新来的哈哈。