iOS WeatherKit, how to fetch hourly forecast

393 views Asked by At

I am successfully fetching current weather conditions with this pattern:

var weatherDescription: String {
  let description = weather?.currentWeather.condition.description ?? "Loading..."
  return description
}

However, when I am trying to fetch the hourly forecast and trying to print it, it is empty.

var hourlyWeatherForecast: Forecast<HourWeather> {
  let forecast = (weather?.hourlyForecast)! //TODO: handle error case
  print (forecast)
  return forecast
}

I am a hobby programmer with very basic skills. Any help is appreciated!

Full code of this class:

//
//  WeatherKitManager.swift
//  FranzFahrenheitv2
//
//  Created by Björn Schefzyk on 3/25/23.
//

import Foundation
import WeatherKit

@MainActor class WeatherKitManager: ObservableObject {
    
    @Published var weather: Weather?
    
    func getWeather(latitude: Double, longitude: Double) async {
        do {
            weather = try await Task.detached(priority: .userInitiated) {
                return try await WeatherService.shared.weather(for: .init(latitude: latitude, longitude: longitude))
            }.value
            //print("Weather: \(String(describing: weather))")
        } catch {
            fatalError("\(error)")
        }
    }
    
    var symbol: String {
        weather?.currentWeather.symbolName ?? "xmark"
    }
    
    var tempC: String {
        let temp =
        Int(weather?.currentWeather.temperature.value ?? 0)
        let convert = String(temp) + "°C"
        return convert
    }
    
    var tempF: String {
        let temp =
        Int(weather?.currentWeather.temperature.converted(to: .fahrenheit).value ?? 0)
        let convert = String(temp) + "°F"
        return convert
    }
    
    var weatherDescription: String {
        let description = weather?.currentWeather.condition.description ?? "Loading..."
        return description
    }
    
    var hourlyWeatherForecast: Forecast<HourWeather> {
        let forecast = (weather?.hourlyForecast)! //TODO: handle error case
        print (forecast)
        return forecast
    }
}

1

There are 1 answers

0
Björn On

The issue was I didn't have this variable hooked up to any View :facepalm: