swiftweatherkit

WeatherKit (Swift) check if will be raining in current day and get only next hour forecast


Playing with WeatherKit in Swiftui recently (very new to the language). I'm working on a simple weather app and I'm trying to achieve two things:

I'm already displaying the conditions for the current weather. Which is the best approach?

This is the function I'm using to get the current weather:

  func getWeather() async {
    do {
        weather = try await Task.detached(priority: .userInitiated) {
            return try await WeatherService.shared.weather(for: .init(latitude: 42.28851, longitude: 13.55401))  // Coordinates for SAN PIO just as example coordinates
        }.value
    } catch {
        fatalError("\(error)")
    }
}

I'm getting the "next hour" condition symbol (and converting it into a corresponding emoji) with:

 var hourlyWeatherForecast: String {
    
    let nextHourWeather = weather?.hourlyForecast.forecast.first?.condition.emoji
    
    return nextHourWeather ?? "Waiting"
}

but struggling to check if rain (or drizzle, or thunderstorms, etc...) is expected for the current day.


Solution

    1. Get hourly and daily forecast.

    2. Get the forecast for today by extracting the information with

      daily.forecast.first{ Calendar.current.isDateInToday($0.date) }
      

    and check if the condition is rainy.

    1. If true get the forecast for the next hour by filtering the hourly forecast similar to 2. but comparing the hour component

    Edit:

    To get also daily and hourly forecast use the including parameter:

    let (current, daily, hourly) = try await WeatherService.shared.weather(for: .init(latitude: 42.28851, longitude: 13.55401), including: .current, .daily, .hourly)
    

    You can check for you desired condition pretty simply. Inside the WeatherCondition extension add

    var isRaining : Bool {
        switch self {
            case .rain, .drizzle, .thunderstorms: return true
            default: return false
        }
    }
    

    Add as many cases as you like in the true branch.