weatherkit
dpearson2699/swift-ios-skills
Fetch WeatherKit forecasts, alerts, and attribution for iOS 18+ apps using Swift 6.3.
What is weatherkit?
Provides access to Apple's WeatherKit API for current conditions, hourly/daily forecasts, weather alerts, and historical comparisons. Use when building weather features in iOS apps, displaying forecasts or alerts, caching responses, or managing WeatherKit query limits and attribution requirements.
- Fetch current weather conditions with temperature, wind, humidity, and UV index
- Retrieve hourly (25 hours) and daily (10 days) forecasts with customizable date ranges
- Access weather alerts with severity, summary, and affected regions
- Query minute-level precipitation forecasts in supported regions
- Retrieve historical weather comparisons and significant weather changes (iOS 18+)
- Display required Apple Weather attribution and legal links
How to install weatherkit
npx skills add https://github.com/dpearson2699/swift-ios-skills --skill weatherkit- Enable WeatherKit capability in Xcode
- Enable WeatherKit for App ID in Apple Developer portal
- Add NSLocationWhenInUseUsageDescription to Info.plist if using device location
- Active Apple Developer Program membership
- Swift 6.3 and iOS 18+
How to use weatherkit
- 1.Import WeatherKit and CoreLocation in your Swift file
- 2.Create a WeatherService instance using WeatherService.shared or WeatherService()
- 3.Call weatherService.weather(for: location) to fetch all datasets or use selective queries with .current, .hourly, .daily, .alerts, etc.
- 4.Format temperatures using Measurement<UnitTemperature>.formatted() to respect user locale
- 5.Display WeatherService.shared.attribution and legalPageURL alongside weather data
- 6.For custom date ranges, use WeatherQuery with startDate and endDate parameters
- 7.Check WeatherMetadata.expirationDate to determine if cached data is fresh
- 8.Handle optional returns (minute forecast, alerts, changes) with conditional binding
Use cases
- Build a weather dashboard showing current conditions and 10-day forecast
- Display active weather alerts with severity levels and detail links
- Implement a tomorrow-specific forecast view using local day intervals
- Cache WeatherKit responses and check expiration dates for freshness
- Minimize API usage by selectively querying only needed datasets (current, hourly, daily, alerts)
- iOS app developers building weather features
- Weather app creators needing multi-day forecasts and alerts
- Developers integrating weather data into travel, fitness, or outdoor apps
- Teams managing API quotas and response caching
weatherkit FAQ
Daily and hourly forecasts can include historical data from August 1, 2021. Forecasts are available up to 10 days in the future, with each request returning at most 10 daily days or about 240 hourly hours.
Use selective queries with specific WeatherQuery types (.current, .hourly, .daily, .alerts) instead of fetching all datasets. Only request the data you need to display.
No, minute forecasts are available only in limited regions and return an optional Forecast<MinuteWeather>?. Check availability before relying on this data.
You must display WeatherService.shared.attribution and include the legalPageURL link. Alert details require non-optional alert.detailsURL links for proper attribution.
Fetch alerts with .alerts query, check the optional weatherAlerts array, and display severity, summary, and detailsURL. Note that alert.region is optional but detailsURL is required.
Full instructions (SKILL.md)
Source of truth, from dpearson2699/swift-ios-skills.
name: weatherkit description: "Fetch WeatherKit current, minute, hourly, and daily forecasts; weather alerts; iOS 18+ changes, historical comparisons, summaries, and statistics; and required Apple Weather attribution. Use when integrating weather data, showing forecasts or alerts, caching WeatherKit responses, displaying attribution, or reviewing WeatherKit query limits in iOS apps."
WeatherKit
Fetch current conditions, hourly and daily forecasts, weather alerts, and
historical statistics using WeatherService. Display required Apple Weather
attribution. Targets Swift 6.3 / iOS 26+.
Contents
- Setup
- Fetching Current Weather
- Forecasts
- Weather Alerts
- Selective Queries
- Context Queries
- Attribution
- Availability
- Common Mistakes
- Review Checklist
- References
Setup
Project Configuration
- Enable the WeatherKit capability in Xcode (adds the entitlement)
- Enable WeatherKit for your App ID in the Apple Developer portal
- Add
NSLocationWhenInUseUsageDescriptionto Info.plist if using device location - WeatherKit requires an active Apple Developer Program membership
Import
import WeatherKit
import CoreLocation
Creating the Service
Use the shared singleton or create an instance. WeatherService conforms to
Sendable; keep app cache and UI state isolated separately.
let weatherService = WeatherService.shared
// or
let weatherService = WeatherService()
Fetching Current Weather
Fetch current conditions for a location. Returns a Weather object with all
available datasets.
WeatherKit temperatures are Measurement<UnitTemperature> values; display them
with .formatted() so units and number formatting follow the user's locale.
func fetchCurrentWeather(for location: CLLocation) async throws -> CurrentWeather {
let weather = try await weatherService.weather(for: location)
return weather.currentWeather
}
// Using the result
func displayCurrent(_ current: CurrentWeather) {
let temp = current.temperature // Measurement<UnitTemperature>
let condition = current.condition // WeatherCondition enum
let symbol = current.symbolName // SF Symbol name
let humidity = current.humidity // Double (0-1)
let wind = current.wind // Wind (speed, direction, gust)
let uvIndex = current.uvIndex // UVIndex
print("\(condition): \(temp.formatted())")
}
Forecasts
Hourly Forecast
Returns 25 contiguous hours starting from the current hour by default.
func fetchHourlyForecast(for location: CLLocation) async throws -> Forecast<HourWeather> {
let weather = try await weatherService.weather(for: location)
return weather.hourlyForecast
}
// Iterate hours
for hour in hourlyForecast {
print("\(hour.date): \(hour.temperature.formatted()), \(hour.condition)")
}
Daily Forecast
Returns 10 contiguous days starting from the current day by default.
func fetchDailyForecast(for location: CLLocation) async throws -> Forecast<DayWeather> {
let weather = try await weatherService.weather(for: location)
return weather.dailyForecast
}
// Iterate days
for day in dailyForecast {
print("\(day.date): \(day.lowTemperature.formatted()) - \(day.highTemperature.formatted())")
print(" Condition: \(day.condition), Precipitation: \(day.precipitationChance)")
}
Custom Date Range
Request forecasts for specific date ranges using WeatherQuery.
Daily and hourly date-range queries use an inclusive startDate and exclusive
endDate. They can include historical data from August 1, 2021. Forecasts are
available up to 10 days in the future; each request returns at most 10 daily
forecast days or about 240 hourly forecast hours.
func fetchExtendedForecast(for location: CLLocation) async throws -> Forecast<DayWeather> {
let startDate = Date.now
let endDate = Calendar.current.date(byAdding: .day, value: 10, to: startDate)!
let forecast = try await weatherService.weather(
for: location,
including: .daily(startDate: startDate, endDate: endDate)
)
return forecast
}
For tomorrow-specific guidance, request the local tomorrow day interval rather than using minute forecasts:
func fetchTomorrowForecast(for location: CLLocation) async throws -> Forecast<DayWeather> {
let calendar = Calendar.current
let tomorrow = calendar.startOfDay(
for: calendar.date(byAdding: .day, value: 1, to: .now)!
)
let dayAfterTomorrow = calendar.date(byAdding: .day, value: 1, to: tomorrow)!
return try await weatherService.weather(
for: location,
including: .daily(startDate: tomorrow, endDate: dayAfterTomorrow)
)
}
Weather Alerts
Fetch active weather alerts for a location. Alerts include severity, summary, and affected regions.
func fetchAlerts(for location: CLLocation) async throws -> [WeatherAlert]? {
let weather = try await weatherService.weather(for: location)
return weather.weatherAlerts
}
// Process alerts
if let alerts = weatherAlerts {
for alert in alerts {
print("Alert: \(alert.summary)")
print("Severity: \(alert.severity)")
print("Region: \(alert.region ?? "Unknown region")")
print("Details: \(alert.detailsURL)") // Non-optional and required for attribution
}
}
For alert dashboards, name WeatherAvailability explicitly when discussing
support checks: it exposes alertAvailability and minuteAvailability only,
not a broad availability matrix for current, hourly, or daily weather.
Selective Queries
Fetch only the datasets you need to minimize API usage and response size. Each
WeatherQuery type maps to one dataset.
Single Dataset
let current = try await weatherService.weather(
for: location,
including: .current
)
// current is CurrentWeather
Multiple Datasets
let (current, hourly, daily) = try await weatherService.weather(
for: location,
including: .current, .hourly, .daily
)
// current: CurrentWeather, hourly: Forecast<HourWeather>, daily: Forecast<DayWeather>
Minute Forecast
Available in limited regions. Returns precipitation forecasts at minute granularity for the next hour.
let minuteForecast = try await weatherService.weather(
for: location,
including: .minute
)
// minuteForecast: Forecast<MinuteWeather>? (nil if unavailable)
Available Query Types
| Query | Return Type | Description |
|---|---|---|
.current | CurrentWeather | Current observed conditions |
.hourly | Forecast<HourWeather> | 25 hours from current hour |
.daily | Forecast<DayWeather> | 10 days from today |
.minute | Forecast<MinuteWeather>? | Next-hour precipitation (limited regions) |
.alerts | [WeatherAlert]? | Active weather alerts |
.availability | WeatherAvailability | Alert and minute forecast availability only |
.changes | WeatherChanges? | Significant upcoming weather changes (iOS 18+) |
.historicalComparisons | HistoricalComparisons? | Current weather compared to historical averages (iOS 18+) |
Dashboard Review Checklist
For a current-temperature and alert dashboard review, explicitly cover:
- Selective
.current, .alertsqueries instead ofweather(for:)for every dataset - No unconditional
onAppear/.tasknetwork fetch; use model or cacheloadIfNeeded WeatherMetadata.expirationDatecache freshnessWeatherService.shared.attribution, mark URLs, andlegalPageURLbeside weather data- Optional
alert.region, non-optionalalert.detailsURL, and alert detail links WeatherAvailabilityonly foralertAvailabilityandminuteAvailabilityMeasurement<UnitTemperature>.formatted()for displayed temperatures- WeatherKit capability/App ID setup and location permission when using device location
Context Queries
Use the iOS 18+ context queries when the app needs to explain why today's weather matters, not just display raw forecast values. Both query results are optional.
For "unusual tomorrow" or "what is changing?" features, request both .changes
and .historicalComparisons. Use .changes for significant upcoming changes,
then use .historicalComparisons to explain how current or forecast conditions
compare with historical averages.
let (changes, comparisons) = try await weatherService.weather(
for: location,
including: .changes, .historicalComparisons
)
For historical statistics, use the WeatherService statistics and summary
methods rather than WeatherQuery. In variadic including: calls, state that
tuple result order matches the query argument order. Load
references/weatherkit-patterns.md when implementing daily summaries, daily
statistics, hourly statistics, or monthly statistics.
Use statistics properties such as averagePrecipitationProbability, not
forecast-only DayWeather.precipitationChance, in statistics examples.
Attribution
Apple requires apps using WeatherKit to display attribution. This is a legal requirement.
Fetching Attribution
func fetchAttribution() async throws -> WeatherAttribution {
return try await weatherService.attribution
}
Displaying Attribution in SwiftUI
import SwiftUI
import WeatherKit
struct WeatherAttributionView: View {
let attribution: WeatherAttribution
@Environment(\.colorScheme) private var colorScheme
var body: some View {
VStack {
// Display the Apple Weather mark
AsyncImage(url: markURL) { image in
image
.resizable()
.scaledToFit()
.frame(height: 20)
} placeholder: {
EmptyView()
}
// Link to the legal attribution page
Link("Weather data sources", destination: attribution.legalPageURL)
.font(.caption2)
.foregroundStyle(.secondary)
}
}
private var markURL: URL {
colorScheme == .dark
? attribution.combinedMarkDarkURL
: attribution.combinedMarkLightURL
}
}
Attribution Properties
| Property | Use |
|---|---|
combinedMarkLightURL | Apple Weather mark for light backgrounds |
combinedMarkDarkURL | Apple Weather mark for dark backgrounds |
squareMarkURL | Square Apple Weather logo |
legalPageURL | URL to the legal attribution web page |
legalAttributionText | Text alternative when a web view is not feasible |
serviceName | Weather data provider name |
Availability
Check whether weather alerts or minute forecast data are available for a
location. WeatherAvailability reports only alert and minute availability;
other datasets, such as current weather, are expected to be supported for
geographic locations.
func checkAvailability(for location: CLLocation) async throws {
let availability = try await weatherService.weather(
for: location,
including: .availability
)
// Check specific dataset availability
if availability.alertAvailability == .available {
// Safe to fetch alerts
}
if availability.minuteAvailability == .available {
// Minute forecast available for this region
}
}
Common Mistakes
DON'T: Ship without Apple Weather attribution
Omitting attribution violates the WeatherKit terms of service and risks App Review rejection.
// WRONG: Show weather data without attribution
VStack {
Text("72F, Sunny")
}
// CORRECT: Always include attribution
VStack {
Text("72F, Sunny")
WeatherAttributionView(attribution: attribution)
}
DON'T: Fetch all datasets when you only need current conditions
Each dataset query counts against your API quota. Fetch only what you display.
// WRONG: Fetches everything
let weather = try await weatherService.weather(for: location)
let temp = weather.currentWeather.temperature
// CORRECT: Fetch only current conditions
let current = try await weatherService.weather(
for: location,
including: .current
)
let temp = current.temperature
DON'T: Ignore minute forecast unavailability
Minute forecasts return nil in unsupported regions. Force-unwrapping crashes.
// WRONG: Force-unwrap minute forecast
let minutes = try await weatherService.weather(for: location, including: .minute)
for m in minutes! { ... } // Crash in unsupported regions
// CORRECT: Handle nil
if let minutes = try await weatherService.weather(for: location, including: .minute) {
for m in minutes { ... }
} else {
// Minute forecast not available for this region
}
DON'T: Forget the WeatherKit entitlement
Without the capability enabled, WeatherService calls throw at runtime.
// WRONG: No WeatherKit capability configured
let weather = try await weatherService.weather(for: location) // Throws
// CORRECT: Enable WeatherKit in Xcode Signing & Capabilities
// and in the Apple Developer portal for your App ID
DON'T: Make repeated requests without caching
WeatherKit models include metadata.expirationDate. Cache responses until that
expiration instead of inventing a fixed refresh interval. Avoid unconditional
network calls from every onAppear or .task; let an @Observable model,
view model, or cache own loadIfNeeded, and reserve explicit refresh for user
refresh actions or location/query changes.
// WRONG: Fetch on every view appearance
.task {
let weather = try? await fetchWeather()
}
// CORRECT: let the model/cache decide whether a fetch is needed
actor WeatherCache {
private var cached: CurrentWeather?
private var expiresAt: Date?
func current(for location: CLLocation) async throws -> CurrentWeather {
if let cached, let expiresAt, Date.now < expiresAt {
return cached
}
let fresh = try await WeatherService.shared.weather(
for: location, including: .current
)
cached = fresh
expiresAt = fresh.metadata.expirationDate
return fresh
}
}
Review Checklist
- WeatherKit capability enabled in Xcode and Apple Developer portal
- Active Apple Developer Program membership (required for WeatherKit)
- Apple Weather attribution displayed wherever weather data appears
- Attribution mark uses correct color scheme variant (light/dark)
- Legal attribution page linked or
legalAttributionTextdisplayed - Only needed
WeatherQuerydatasets fetched (not fullweather(for:)when unnecessary) - Minute forecast handled as optional (nil in unsupported regions)
- Weather alerts checked for nil before iteration
- Alert detail links use non-optional
detailsURL; optionalregionis nil-safe - Responses cached until each model's
metadata.expirationDate -
WeatherAvailabilityused for alert/minute availability, not as a broad support matrix - Location permission requested before passing
CLLocationto service - Temperature and measurements formatted with
Measurement.formatted()for locale
References
- Extended patterns (SwiftUI dashboard, charts integration, historical statistics): references/weatherkit-patterns.md
- WeatherKit framework
- WeatherService
- WeatherAttribution
- WeatherQuery
- WeatherQuery.daily(startDate:endDate:)
- WeatherQuery.hourly(startDate:endDate:)
- CurrentWeather
- CurrentWeather.temperature
- Measurement.formatted()
- Forecast
- HourWeather
- DayWeather
- WeatherAlert
- WeatherAvailability
- WeatherMetadata.expirationDate
- WeatherQuery.changes
- WeatherQuery.historicalComparisons
- WeatherKit updates
- Bring context to today's weather
- Fetching weather forecasts with WeatherKit
Related skills
More from dpearson2699/swift-ios-skills and the wider catalog.

widgetkit
Build Home Screen, Lock Screen, Control Center, and StandBy widgets for iOS with timeline providers and interactive controls.

accessorysetupkit
Privacy-preserving Bluetooth and Wi-Fi accessory discovery and setup for iOS 18+

activitykit
Build real-time Lock Screen and Dynamic Island Live Activities for iOS with ActivityKit.

adattributionkit
Privacy-preserving ad attribution for iOS 17.4+ measuring conversions without exposing user data.

tech-news-digest
Generate tech news digests with unified source model, quality scoring, and multi-format output. Six-source data collection from RSS feeds, Twitter/X KOLs, GitHub releases, GitHub Trending, Reddit, and web search. Pipeline-based scripts with retry mechanisms and deduplication. Supports Discord, email, and markdown templates.

pdf-to-markdown
[Document Processing] Use when you need to convert PDF files to Markdown with support for native text PDFs and scanned documents (OCR).