Как использовать WeatherKit для получения почасовой температуры?IOS

Программируем под IOS
Ответить Пред. темаСлед. тема
Гость
 Как использовать WeatherKit для получения почасовой температуры?

Сообщение Гость »


Я пытаюсь получить почасовой прогноз температуры из 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
Реклама
Ответить Пред. темаСлед. тема

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

  • Похожие темы
    Ответы
    Просмотры
    Последнее сообщение

Вернуться в «IOS»