Weatherkit

作者 dpearson26998d90fd121a26無授權條款1.1K 個星標收錄於 2026年10月8日更新於 2026年10月8日儲存庫2 個月前更新

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.

AI 產生的概覽

指導 iOS 開發者使用 WeatherService 取得 WeatherKit 預報、警報與署名資訊。

功能
此技能提供在 iOS 應用程式中使用 Apple WeatherKit 框架的參考說明。內容涵蓋專案設定與權限、取得目前天氣、逐小時與逐日預報、分鐘級降水、天氣警報、選擇性查詢、iOS 18+ 情境查詢、可用性檢查,以及 Apple 要求的 Weather 署名。它也列出常見錯誤與審查清單,並指向配套參考文件以取得 SwiftUI 儀表板、圖表、快取與歷史統計等延伸模式。
適用情境
適用於在 iOS 應用程式中整合天氣資料、顯示預報或警報、快取 WeatherKit 回應、顯示必要署名,或審查 WeatherKit 查詢限制的情境。適合使用 Swift 中 WeatherService 與 CoreLocation 的開發者。
執行需求
需要 Apple Developer Program 會員資格、在 Xcode 與 Apple Developer 入口網站中啟用 WeatherKit 功能,以及 WeatherKit 與 CoreLocation 框架。使用裝置定位時需定位權限(NSLocationWhenInUseUsageDescription)。此技能不附帶指令碼,僅為說明文件,並含一份配套參考文件。

WeatherKit

Fetch current conditions, hourly and daily forecasts, weather alerts, and historical statistics using WeatherService. Display required Apple Weather attribution.

Contents

Setup

Project Configuration

  1. Enable the WeatherKit capability in Xcode (adds the entitlement)
  2. Enable WeatherKit for your App ID in the Apple Developer portal
  3. Add NSLocationWhenInUseUsageDescription to Info.plist if using device location
  4. WeatherKit requires an active Apple Developer Program membership

Import

swift
import WeatherKitimport CoreLocation

Creating the Service

Use the shared singleton or create an instance. WeatherService conforms to Sendable; keep app cache and UI state isolated separately.

swift
let weatherService = WeatherService.shared// orlet 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.

swift
func fetchCurrentWeather(for location: CLLocation) async throws -> CurrentWeather {    let weather = try await weatherService.weather(for: location)    return weather.currentWeather}
// Using the resultfunc 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.

swift
func fetchHourlyForecast(for location: CLLocation) async throws -> Forecast<HourWeather> {    let weather = try await weatherService.weather(for: location)    return weather.hourlyForecast}
// Iterate hoursfor hour in hourlyForecast {    print("\(hour.date): \(hour.temperature.formatted()), \(hour.condition)")}

Daily Forecast

Returns 10 contiguous days starting from the current day by default.

swift
func fetchDailyForecast(for location: CLLocation) async throws -> Forecast<DayWeather> {    let weather = try await weatherService.weather(for: location)    return weather.dailyForecast}
// Iterate daysfor 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.

swift
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:

swift
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.

swift
func fetchAlerts(for location: CLLocation) async throws -> [WeatherAlert]? {    let weather = try await weatherService.weather(for: location)    return weather.weatherAlerts}
// Process alertsif 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

swift
let current = try await weatherService.weather(    for: location,    including: .current)// current is CurrentWeather

Multiple Datasets

swift
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.

swift
let minuteForecast = try await weatherService.weather(    for: location,    including: .minute)// minuteForecast: Forecast<MinuteWeather>?  (nil if unavailable)

Available Query Types

QueryReturn TypeDescription
.currentCurrentWeatherCurrent observed conditions
.hourlyForecast<HourWeather>25 hours from current hour
.dailyForecast<DayWeather>10 days from today
.minuteForecast<MinuteWeather>?Next-hour precipitation (limited regions)
.alerts[WeatherAlert]?Active weather alerts
.availabilityWeatherAvailabilityAlert and minute forecast availability only
.changesWeatherChanges?Significant upcoming weather changes (iOS 18+)
.historicalComparisonsHistoricalComparisons?Current weather compared to historical averages (iOS 18+)

Context Queries

For "unusual tomorrow" or "what is changing?" features on iOS 18+, request the optional .changes and .historicalComparisons results together: the first reports significant upcoming changes and the second provides historical context.

swift
let (changes, comparisons) = try await weatherService.weather(    for: location,    including: .changes, .historicalComparisons)

Historical summaries and statistics use WeatherService methods rather than WeatherQuery. Load references/weatherkit-patterns.md [blocked] for their tuple ordering, APIs, and statistics-specific properties.

Attribution

Apple requires apps using WeatherKit to display attribution. This is a legal requirement.

Fetching Attribution

swift
func fetchAttribution() async throws -> WeatherAttribution {    return try await weatherService.attribution}

Load references/weatherkit-patterns.md [blocked] for the complete SwiftUI attribution view and cache integration.

Attribution Properties

PropertyUse
combinedMarkLightURLApple Weather mark for light backgrounds
combinedMarkDarkURLApple Weather mark for dark backgrounds
squareMarkURLSquare Apple Weather logo
legalPageURLURL to the legal attribution web page
legalAttributionTextText alternative when a web view is not feasible
serviceNameWeather 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.

swift
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

Display the appropriate Apple Weather mark and link legalPageURL wherever WeatherKit data appears; use legalAttributionText only when the legal page cannot be shown.

DON'T: Fetch all datasets when you only need current conditions

Each dataset query counts against your API quota. Use the selective query shown in Selective Queries and fetch only what the UI displays.

DON'T: Ignore minute forecast unavailability

Minute forecasts are optional in unsupported regions. Check availability and handle the nil result instead of force-unwrapping it.

DON'T: Forget the WeatherKit entitlement

Without the capability enabled, WeatherService calls throw at runtime.

swift
// WRONG: No WeatherKit capability configuredlet 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 interval or fetching on every view appearance. Let a model or cache own loadIfNeeded; the complete actor pattern is in references/weatherkit-patterns.md [blocked].

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 legalAttributionText displayed
  • Only needed WeatherQuery datasets fetched (not full weather(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; optional region is nil-safe
  • Responses cached until each model's metadata.expirationDate
  • WeatherAvailability used for alert/minute availability, not as a broad support matrix
  • Location permission requested before passing CLLocation to service
  • Temperature and measurements formatted with Measurement.formatted() for locale

References

來源與署名

來源:dpearson2699/swift-ios-skills位於skills/weatherkit提交8d90fd1

授權條款: 無授權條款

內容歸原作者所有。SourceWeft 從公開儲存庫中收錄這些內容。

檢舉或申請下架

更多來自 dpearson2699/swift-ios-skills 的技能

Widgetkit

dpearson2699

指導實作、審查與改進 iOS、iPadOS、watchOS 與 CarPlay 上的 WidgetKit 小工具與控制項。

Software Development1.1K2 個月前更新

Vision Framework

dpearson2699

Implement computer vision features including text recognition (OCR), face detection, barcode scanning, image segmentation, object tracking, and document scanning in iOS apps. Covers both the modern Swift-native Vision API (iOS 18+) and legacy VNRequest patterns, VisionKit DataScannerViewController for live camera scanning, and CoreMLRequest/VNCoreMLRequest for custom model inference. Use when adding OCR, barcode scanning, face detection, or custom Core ML model inference with Vision.

待分類1.1K2 個月前更新

Tipkit

dpearson2699

Implement and review Apple TipKit feature-discovery UI for iOS 17+ apps. Use when adding or auditing in-app tips, contextual help, coach marks, Tip, TipView, popoverTip, rules, events, actions, display frequency, testing overrides, reusable tip identifiers, or iOS 18+ TipGroup and CloudKit tip sync; avoid for generic SwiftUI navigation or layout outside tip presentation.

待分類1.1K2 個月前更新

Tabletopkit

dpearson2699

指導使用 TabletopKit 在 visionOS 上打造多人空間桌遊,涵蓋棋具、座位、動作與 RealityKit 算繪。

Software Development1.1K2 個月前更新

Swiftui Webkit

dpearson2699

指導在 iOS 26 及更新版本的 SwiftUI App 中使用 WebKit for SwiftUI 嵌入與控制網頁內容。

Software Development1.1K2 個月前更新

Swiftui Uikit Interop

dpearson2699

指導使用可表示視圖、託管控制器、協調器與共享可觀察狀態來橋接 UIKit 與 SwiftUI。

Software Development1.1K2 個月前更新