Мое приложение должно использовать название города, которое String - поместите его в fetchWeather. () func, загружаем данные и делаем все, а после этого запускаем функцию getWeather() в ListView и обновляем значения (город), которые я использую в пользовательском интерфейсе.
Код:
Менеджер погоды:
Код: Выделить всё
import Foundation
struct WeatherManager {
let weatherURL = "https://api.openweathermap.org/data/2.5/weather?appid=APP_ID&units=metric"
func fetchWeather(cityName: String) {
let urlString = "\(weatherURL)&q=\(cityName)"
performRequest(with: urlString)
return
}
func performRequest(with urlString: String) {
if let url = URL(string: urlString) {
let session = URLSession(configuration: .default)
let task = session.dataTask(with: url) { (data, response, error) in
if error != nil {
return
}
if let safeData = data {
if let weather = self.parseJSON(safeData) {
let listVC = ListView()
DispatchQueue.main.async {
listVC.getWeather(weather: weather)
}
}
}
}
task.resume()
}
}
func parseJSON(_ weatherData: Data) -> WeatherModel? {
let decoder = JSONDecoder()
do {
let decodedData = try decoder.decode(WeatherData.self, from: weatherData)
let id = decodedData.weather[0].id
let temp = decodedData.main.temp
let name = decodedData.name
let weather = WeatherModel(conditionId: id, cityName: name, temperature: temp)
return weather
} catch {
return nil
}
}
}
Код: Выделить всё
import Foundation
struct WeatherModel {
var conditionId: Int
var cityName: String
var temperature: Double
var temperatureString: String {
return String(format: "%.1f", temperature)
}
var conditionName: String {
switch conditionId {
case 200...232:
return "cloud.bolt"
case 300...321:
return "cloud.drizzle"
case 500...531:
return "cloud.rain"
case 600...622:
return "cloud.snow"
case 701...781:
return "cloud.fog"
case 800:
return "sun.max"
case 801...804:
return "cloud.bolt"
default:
return "cloud"
}
}
}
Код: Выделить всё
import Foundation
struct WeatherData: Codable {
let name: String
let main: Main
let weather: [Weather]
}
struct Main: Codable {
let temp: Double
}
struct Weather: Codable {
let description: String
let id: Int
}
Код: Выделить всё
import SwiftUI
struct ListView: View{
@State var weatherMenager = WeatherManager()
@State var city : String = ""
@State var textFieldText : String = ""
func getWeather(weather : WeatherModel){ //
print(weather.cityName) //works - print data in console
print(weather.temperatureString)// works - print data in console
self.city = weather.cityName
print(city) // doesn't print data just like it's empty string
}
.... more code which dont't really metter - just swiftui code
Подробнее здесь: https://stackoverflow.com/questions/712 ... -in-swiftu
Мобильная версия