Eventkit

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

Create, read, and manage calendar events and reminders using EventKit and EventKitUI. Use when adding events to the user's calendar, creating reminders, setting recurrence rules, requesting calendar or reminders access, presenting event editors, choosing calendars, handling alarms, observing calendar changes, or working with EKEventStore, EKEvent, EKReminder, EKCalendar, EKRecurrenceRule, EKEventEditViewController, EKCalendarChooser, or EventKitUI views.

AI 產生的概覽

指導 iOS 開發者使用 EventKit 與 EventKitUI 處理行事曆事件、提醒事項、重複規則、鬧鐘與授權。

功能
此技能為在 iOS 應用程式中使用 Apple 的 EventKit 與 EventKitUI 框架提供參考指引。內容涵蓋授權路徑、建立與取得事件、提醒事項、重複規則、鬧鐘、系統編輯器(例如 EKEventEditViewController 與 EKCalendarChooser),以及觀察儲存區變更。它也列出常見錯誤與審查清單,並在隨附的參考檔案中提供延伸模式。
適用情境
適用於在 iOS 應用程式中加入行事曆事件或提醒事項、要求行事曆或提醒事項存取權、設定重複規則或鬧鐘、顯示系統事件編輯器或行事曆選擇器,或觀察 EventKit 儲存區變更的情境。
執行需求
需要具備 iOS 開發環境,使用 EventKit 與 EventKitUI 框架,並設定對應的 Info.plist 用途說明鍵。此技能不含指令碼,僅為說明文件,並附帶一份參考文件。

EventKit

Use EventKit for calendar and reminder authorization, CRUD, recurrence, alarms, and system editors.

Contents

Availability

  • iOS 17+: Use granular full/write-only request methods; legacy requestAccess(to:) no longer prompts and throws. The system event editor can create an event without app calendar access. For iOS 10–16, guard those APIs, use the legacy request plus NSCalendarsUsageDescription / NSRemindersUsageDescription; EventKitUI may also need NSContactsUsageDescription.
  • iOS 26+: The typed EKEventStore.EventStoreChanged / .changed message is available behind a guard. Keep EKEventStoreChanged for earlier systems.

Setup

Info.plist Keys

Add the usage description for the access path selected in Authorization. Do not request broader access merely to simplify the setup path.

The authorization-free system editor path needs no calendar usage string. Direct writes need write-only or full access; reads need full access. Reminders have only full access.

Event Store

Create a single EKEventStore instance and reuse it. Do not mix objects from different event stores.

swift
import EventKit
let eventStore = EKEventStore()

Authorization

Request the narrowest access that matches the feature. Apply the versioned request path in Availability.

KeyAccess Level
NSCalendarsFullAccessUsageDescriptionRead + write events
NSCalendarsWriteOnlyAccessUsageDescriptionDirect write-only event creation
NSRemindersFullAccessUsageDescriptionRead + write reminders

Full Access to Events

Call try await eventStore.requestFullAccessToEvents() when the app needs to read, edit, delete, or fetch calendar events.

Write-Only Access to Events

Use when your app only creates events (e.g., saving a booking) and does not need to read existing events.

Call try await eventStore.requestWriteOnlyAccessToEvents() before direct EventKit writes that do not use EKEventEditViewController.

Write-only access can create events but cannot fetch calendars or events, including app-created events. Use full access for later query, verification, modification, or sync.

Full Access to Reminders

Call try await eventStore.requestFullAccessToReminders() before reading, creating, editing, or deleting reminders.

Checking Authorization Status

Use EKEventStore.authorizationStatus(for: .event) or .reminder before work. Handle .notDetermined, .fullAccess, .writeOnly, .restricted, .denied, and @unknown default; only .fullAccess supports event/reminder reads.

Creating Events

swift
func createEvent(    title: String,    startDate: Date,    endDate: Date,    calendar: EKCalendar? = nil) throws {    let event = EKEvent(eventStore: eventStore)    event.title = title    event.startDate = startDate    event.endDate = endDate    event.calendar = calendar ?? eventStore.defaultCalendarForNewEvents
    try eventStore.save(event, span: .thisEvent)}

Setting a Specific Calendar

swift
// List writable calendarslet calendars = eventStore.calendars(for: .event)    .filter { $0.allowsContentModifications }
// Use the first writable calendar, or the defaultlet targetCalendar = calendars.first ?? eventStore.defaultCalendarForNewEventsevent.calendar = targetCalendar

Adding Structured Location

swift
import CoreLocation
let location = EKStructuredLocation(title: "Apple Park")location.geoLocation = CLLocation(latitude: 37.3349, longitude: -122.0090)event.structuredLocation = location

Fetching Events

After the full-access gate in Authorization, use a date-range predicate to query events. The events(matching:) method returns occurrences of recurring events expanded within the range. Event predicates are capped to a four-year span, and events(matching:) / enumerateEvents(matching:using:) are synchronous and return only committed events.

swift
func fetchEvents(from start: Date, to end: Date) -> [EKEvent] {    let predicate = eventStore.predicateForEvents(        withStart: start,        end: end,        calendars: nil  // nil = all calendars    )    return eventStore.events(matching: predicate)        .sorted { $0.startDate < $1.startDate }}

Fetching a Single Event by Identifier

swift
if let event = eventStore.event(withIdentifier: savedEventID) {    print(event.title ?? "No title")}

Reminders

Creating a Reminder

swift
func createReminder(title: String, dueDate: Date) throws {    let reminder = EKReminder(eventStore: eventStore)    reminder.title = title    reminder.calendar = eventStore.defaultCalendarForNewReminders()
    let dueDateComponents = Calendar.current.dateComponents(        [.year, .month, .day, .hour, .minute],        from: dueDate    )    reminder.dueDateComponents = dueDateComponents
    try eventStore.save(reminder, commit: true)}

Fetching Reminders

Reminder fetches are asynchronous and return through a completion handler.

swift
func fetchIncompleteReminders() async -> [EKReminder] {    let predicate = eventStore.predicateForIncompleteReminders(        withDueDateStarting: nil,        ending: nil,        calendars: nil    )
    return await withCheckedContinuation { continuation in        eventStore.fetchReminders(matching: predicate) { reminders in            continuation.resume(returning: reminders ?? [])        }    }}

Completing a Reminder

swift
func completeReminder(_ reminder: EKReminder) throws {    reminder.isCompleted = true    try eventStore.save(reminder, commit: true)}

Recurrence Rules

Use EKRecurrenceRule to create repeating events or reminders.

Simple Recurrence

swift
// Every week, indefinitelylet weeklyRule = EKRecurrenceRule(    recurrenceWith: .weekly,    interval: 1,    end: nil)event.addRecurrenceRule(weeklyRule)
// Every 2 weeks, ending after 10 occurrenceslet biweeklyRule = EKRecurrenceRule(    recurrenceWith: .weekly,    interval: 2,    end: EKRecurrenceEnd(occurrenceCount: 10))
// Monthly, ending on a specific datelet monthlyRule = EKRecurrenceRule(    recurrenceWith: .monthly,    interval: 1,    end: EKRecurrenceEnd(end: endDate))

Complex Recurrence

swift
// Every Monday and Wednesdaylet days = [    EKRecurrenceDayOfWeek(.monday),    EKRecurrenceDayOfWeek(.wednesday)]
let complexRule = EKRecurrenceRule(    recurrenceWith: .weekly,    interval: 1,    daysOfTheWeek: days,    daysOfTheMonth: nil,    monthsOfTheYear: nil,    weeksOfTheYear: nil,    daysOfTheYear: nil,    setPositions: nil,    end: nil)event.addRecurrenceRule(complexRule)

Editing Recurring Events

When saving changes to a recurring event, specify the span:

swift
// Change only this occurrencetry eventStore.save(event, span: .thisEvent)
// Change this and all future occurrencestry eventStore.save(event, span: .futureEvents)

Alarms

Attach alarms to events or reminders to trigger notifications.

swift
// 15 minutes beforelet alarm = EKAlarm(relativeOffset: -15 * 60)event.addAlarm(alarm)
// At an absolute datelet absoluteAlarm = EKAlarm(absoluteDate: alertDate)event.addAlarm(absoluteAlarm)

For reminder geofences, put an EKStructuredLocation and .enter / .leave proximity on an EKAlarm, then add it to the reminder. See references/eventkit-patterns.md [blocked] for the full location-based reminder pattern.

EventKitUI Controllers

EKEventEditViewController — Create/Edit Events

Present the system event editor for creating or editing events.

On the authorization-free path in Availability, the editor runs out of process with its own calendar access. Do not inspect the dismissed controller to learn what was saved; refetch only with separate full access.

swift
import EventKitUI
class EventEditorCoordinator: NSObject, EKEventEditViewDelegate {    let eventStore = EKEventStore()
    func presentEditor(from viewController: UIViewController) {        let editor = EKEventEditViewController()        editor.eventStore = eventStore        editor.editViewDelegate = self        viewController.present(editor, animated: true)    }
    func eventEditViewController(        _ controller: EKEventEditViewController,        didCompleteWith action: EKEventEditViewAction    ) {        switch action {        case .saved:            // Event saved            break        case .canceled:            break        case .deleted:            break        @unknown default:            break        }        controller.dismiss(animated: true)    }}

EKEventViewController — View an Event

swift
import EventKitUI
let viewer = EKEventViewController()viewer.event = existingEventviewer.allowsEditing = truenavigationController?.pushViewController(viewer, animated: true)

EKCalendarChooser — Select Calendars

EKCalendarChooser requires write-only or full calendar access. In write-only apps, the chooser behaves as writable-calendars-only and only allows a single writable calendar selection.

swift
let chooser = EKCalendarChooser(    selectionStyle: .multiple,    displayStyle: .allCalendars,    entityType: .event,    eventStore: eventStore)chooser.showsDoneButton = truechooser.showsCancelButton = truechooser.delegate = selfpresent(UINavigationController(rootViewController: chooser), animated: true)

Observing Changes

Register for EKEventStoreChanged notifications to keep your UI in sync when events are modified outside your app (e.g., by the Calendar app or a sync).

swift
NotificationCenter.default.addObserver(    forName: .EKEventStoreChanged,    object: eventStore,    queue: .main) { [weak self] _ in    self?.refreshEvents()}

Always re-fetch events after receiving this notification. Previously fetched EKEvent, EKReminder, and EKCalendar objects may be stale. The notification is posted on the main actor.

Common Mistakes

DON'T: Use legacy requestAccess(to:) on current systems

swift
// WRONG: Legacy request API on current systemseventStore.requestAccess(to: .event) { granted, error in }
// CORRECT: Use the granular async methodslet granted = try await eventStore.requestFullAccessToEvents()

Keep it only in the compatibility fallback from Availability.

DON'T: Save events to a read-only calendar

swift
// WRONG: No check -- will throw if calendar is read-onlyevent.calendar = someCalendartry eventStore.save(event, span: .thisEvent)
// CORRECT: Verify the calendar allows modificationsguard someCalendar.allowsContentModifications else {    event.calendar = eventStore.defaultCalendarForNewEvents    return}event.calendar = someCalendartry eventStore.save(event, span: .thisEvent)

DON'T: Ignore timezone when creating events

swift
// WRONG: Event appears at wrong time for traveling usersevent.startDate = Date()event.endDate = Date().addingTimeInterval(3600)
// CORRECT: Set the timezone explicitly for location-specific eventsevent.timeZone = TimeZone(identifier: "America/New_York")event.startDate = startDateevent.endDate = endDate

DON'T: Forget to commit batched saves

swift
// WRONG: Changes never persistedtry eventStore.save(event1, span: .thisEvent, commit: false)try eventStore.save(event2, span: .thisEvent, commit: false)// Missing commit!
// CORRECT: Commit after batchingtry eventStore.save(event1, span: .thisEvent, commit: false)try eventStore.save(event2, span: .thisEvent, commit: false)try eventStore.commit()

DON'T: Mix EKObjects from different event stores

swift
// WRONG: Event fetched from storeA, saved to storeBlet event = storeA.event(withIdentifier: id)!try storeB.save(event, span: .thisEvent) // Undefined behavior
// CORRECT: Use the same store throughoutlet event = eventStore.event(withIdentifier: id)!try eventStore.save(event, span: .thisEvent)

Review Checklist

  • Correct Info.plist usage description keys added for calendars and/or reminders
  • Authorization follows the version split in Availability
  • Write-only calendar access used only for direct event creation, not event/calendar reads
  • Authorization status checked before fetching or saving
  • Full access required before any event or reminder fetch
  • Single EKEventStore instance reused across the app
  • Events saved to a writable calendar (allowsContentModifications checked)
  • Recurring event saves specify correct EKSpan (.thisEvent vs .futureEvents)
  • Batched saves validate writable calendars, stage with commit: false, call throwing commit(), and on failure reset() unsaved state, discard every invalidated EKObject, then refetch or reconstruct before retry
  • EKEventStoreChanged notification observed to refresh stale data
  • Change observation uses the classic notification or guarded typed message per Availability
  • Timezone set explicitly for location-specific events
  • EKObjects not shared across different event store instances
  • EventKitUI delegates dismiss controllers in completion callbacks

References

來源與署名

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

授權條款: 無授權條款

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

檢舉或申請下架

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

Widgetkit

dpearson2699

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

Software Development1.1K2 個月前更新

Weatherkit

dpearson2699

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

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 個月前更新