Программируем под IOS
Гость
Как использовать WeatherKit для получения почасовой температуры?
Сообщение
Гость » 13 мар 2024, 18:39
Я пытаюсь получить почасовой прогноз температуры из WeatherKit; однако я продолжаю получать сообщение об ошибке «Невозможно присвоить значение типа «Прогноз» типу «[HourWeather]». Я получаю сообщение об ошибке в функции updateHourlyWeather. Целью получения почасовой погоды является возможность использовать почасовую погоду построить линейную диаграмму температуры окружающей среды.
Код: Выделить всё
import SwiftUI
import CoreLocation
import WeatherKit
import Foundation
@MainActor
class WeatherData: ObservableObject {
static let shared = WeatherData()
private let service = WeatherService.shared
@Published var currentWeather: CurrentWeather?
@Published var hourlyForecast: [HourWeather] = []
func updateCurrentWeather(userLocation: CLLocation) {
Task.detached(priority: .userInitiated) {
do {
let forcast = try await self.service.weather(
for: userLocation,
including: .current)
DispatchQueue.main.async {
self.currentWeather = forcast
}
} catch {
print(error.localizedDescription)
}
}
}
func updateHourlyWeather(userLocation: CLLocation) {
Task.detached(priority: .userInitiated) {
do {
let forcast = try await self.service.weather(
for: userLocation,
including: .hourly)
DispatchQueue.main.async {
self.hourlyForecast = forcast
}
} catch {
print(error.localizedDescription)
}
}
}
}
struct LocalizedWeatherView: View {
@ObservedObject var weatherDataHelper = WeatherData.shared
@ObservedObject var userLocationHelper = WeatherLocationManager.shared
var body: some View {
Form {
if let currentWeather = weatherDataHelper.currentWeather {
Section {
Label(currentWeather.temperature.formatted(), systemImage: "thermometer")
Label("\(Int(currentWeather.humidity * 100))%", systemImage: "humidity.fill")
Label(currentWeather.isDaylight ? "Day time" : "Night time", systemImage: currentWeather.isDaylight ? "sun.max.fill" : "moon.stars.fill")
} header: {
HStack {
Spacer()
Image(systemName: currentWeather.symbolName)
.font(.system(size: 60))
Spacer()
}
}
}
Section {
if userLocationHelper.userLocation == nil {
Button("Load user current location") {
loadUserCurrentLocation()
}
}
Button("Fetch current weather") {
loadCurrentWeatherData()
}
}
}
}
func loadUserCurrentLocation() {
userLocationHelper.requestPermission()
userLocationHelper.locationManager.requestLocation()
}
func loadCurrentWeatherData() {
guard let userLocation = WeatherLocationManager.shared.userLocation else {
return
}
Task.detached { @MainActor in
weatherDataHelper.updateCurrentWeather(userLocation: userLocation)
}
}
}
Источник:
https://stackoverflow.com/questions/781 ... emperature
1710344383
Гость
Я пытаюсь получить почасовой прогноз температуры из WeatherKit; однако я продолжаю получать сообщение об ошибке «Невозможно присвоить значение типа «Прогноз» типу «[HourWeather]». Я получаю сообщение об ошибке в функции updateHourlyWeather. Целью получения почасовой погоды является возможность использовать почасовую погоду построить линейную диаграмму температуры окружающей среды. [code]import SwiftUI import CoreLocation import WeatherKit import Foundation @MainActor class WeatherData: ObservableObject { static let shared = WeatherData() private let service = WeatherService.shared @Published var currentWeather: CurrentWeather? @Published var hourlyForecast: [HourWeather] = [] func updateCurrentWeather(userLocation: CLLocation) { Task.detached(priority: .userInitiated) { do { let forcast = try await self.service.weather( for: userLocation, including: .current) DispatchQueue.main.async { self.currentWeather = forcast } } catch { print(error.localizedDescription) } } } func updateHourlyWeather(userLocation: CLLocation) { Task.detached(priority: .userInitiated) { do { let forcast = try await self.service.weather( for: userLocation, including: .hourly) DispatchQueue.main.async { self.hourlyForecast = forcast } } catch { print(error.localizedDescription) } } } } struct LocalizedWeatherView: View { @ObservedObject var weatherDataHelper = WeatherData.shared @ObservedObject var userLocationHelper = WeatherLocationManager.shared var body: some View { Form { if let currentWeather = weatherDataHelper.currentWeather { Section { Label(currentWeather.temperature.formatted(), systemImage: "thermometer") Label("\(Int(currentWeather.humidity * 100))%", systemImage: "humidity.fill") Label(currentWeather.isDaylight ? "Day time" : "Night time", systemImage: currentWeather.isDaylight ? "sun.max.fill" : "moon.stars.fill") } header: { HStack { Spacer() Image(systemName: currentWeather.symbolName) .font(.system(size: 60)) Spacer() } } } Section { if userLocationHelper.userLocation == nil { Button("Load user current location") { loadUserCurrentLocation() } } Button("Fetch current weather") { loadCurrentWeatherData() } } } } func loadUserCurrentLocation() { userLocationHelper.requestPermission() userLocationHelper.locationManager.requestLocation() } func loadCurrentWeatherData() { guard let userLocation = WeatherLocationManager.shared.userLocation else { return } Task.detached { @MainActor in weatherDataHelper.updateCurrentWeather(userLocation: userLocation) } } } [/code] Источник: [url]https://stackoverflow.com/questions/78154674/how-to-use-weatherkit-to-fetch-hourly-temperature[/url]