Ios 如何在Swift中设置API响应中的标签文本
我是一个新手Swift程序员,试图学习如何使用API调用 我开始使用OpenWeatherMap制作天气应用程序 我设置了所有设置,能够获取设备的位置,然后获取该位置的天气。我可以在控制台日志中看到该位置的天气 但现在我找不到一种方法来使用它们作为标签文本等。我只能得到城市名称,但不能在课外使用它 所以,我的问题是,我应该如何使用从API获取的JSON数据作为故事板标签 谢谢你的帮助 我的文件: ViewController.swift:主控制器。我获取设备的位置,并使用getWeather获取lat和lon,以便将其发送到WeatherAPI.swift swift:连接到OpenWeatherMap并获取数据。 Weather.swift:获取的API数据的结构。 ViewController.swift 斯威夫特 斯威夫特天气预报 修改getWeather方法参数,使其末尾有一个完成块,如下所示:Ios 如何在Swift中设置API响应中的标签文本,ios,swift,xcode,Ios,Swift,Xcode,我是一个新手Swift程序员,试图学习如何使用API调用 我开始使用OpenWeatherMap制作天气应用程序 我设置了所有设置,能够获取设备的位置,然后获取该位置的天气。我可以在控制台日志中看到该位置的天气 但现在我找不到一种方法来使用它们作为标签文本等。我只能得到城市名称,但不能在课外使用它 所以,我的问题是,我应该如何使用从API获取的JSON数据作为故事板标签 谢谢你的帮助 我的文件: ViewController.swift:主控制器。我获取设备的位置,并使用getWeather获取
class WeatherAPI {
//...
func getWeather(lat : Double, lon: Double, completion: @escaping (CurrentLocalWeather) -> Void) {
//...
let task = session.dataTask(with: url) { data, response, error in
//...
do {
let weatherItems = try JSONDecoder().decode(CurrentLocalWeather.self, from: data!)
completion(weatherItems)
} catch {
print("JSON error: \(error)")
}
}
task.resume()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location:CLLocationCoordinate2D = manager.location!.coordinate
let weather = WeatherAPI()
weather.getWeather(lat: location.latitude, lon: location.longitude) { weather in
print(weather.name)
}
}
用这种方法:
class WeatherAPI {
//...
func getWeather(lat : Double, lon: Double, completion: @escaping (CurrentLocalWeather) -> Void) {
//...
let task = session.dataTask(with: url) { data, response, error in
//...
do {
let weatherItems = try JSONDecoder().decode(CurrentLocalWeather.self, from: data!)
completion(weatherItems)
} catch {
print("JSON error: \(error)")
}
}
task.resume()
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location:CLLocationCoordinate2D = manager.location!.coordinate
let weather = WeatherAPI()
weather.getWeather(lat: location.latitude, lon: location.longitude) { weather in
print(weather.name)
}
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
let location:CLLocationCoordinate2D = manager.location!.coordinate
let weather = WeatherAPI()
weather.getWeather(lat: location.latitude, lon: location.longitude) { weather in
print(weather.name)
}
}