This is documentation for the next SDK version. For up-to-date documentation, see the latest version (SDK 55).
Expo 日历(next)
一个提供用于与设备系统日历、事件、提醒事项及相关记录交互的 API 的库。
For the complete documentation index, see llms.txt. Use this Use this file to discover all available pages.
Calendar API的next版本包含在expo-calendar库中。它可以与之前的 API 一起使用,并提供一种简化的、面向对象的方式来执行日历操作。
为了提供更快的更新,expo-calendar/next目前在 Expo Go 和 Snack 中不受支持。要使用它,请创建一个 开发构建。
expo-calendar 提供了一个用于与设备系统日历、事件、提醒以及相关记录交互的 API。
此外,它还提供了用于启动 系统提供的日历 UI 的方法,以允许用户查看或编辑事件。在 iOS 上,它们会以模态形式呈现 EKEventViewController 或 EKEventEditViewController。
安装
- npx expo install expo-calendarIf you are installing this in an existing React Native app, make sure to install expo in your project.
在 app config 中进行配置
如果你在项目中使用 config plugins(Continuous Native Generation (CNG)),你可以使用 expo-calendar 内置的 config plugin 进行配置。该插件允许你配置一些无法在运行时设置的属性,并且这些属性需要构建新的应用二进制文件后才会生效。如果你的应用不使用 CNG,那么你需要手动配置该库。
Example app.json with config plugin
{ "expo": { "plugins": [ [ "expo-calendar", { "calendarPermission": "应用需要访问你的日历。" } ] ] } }
Configurable properties
| Name | Default | Description |
|---|---|---|
calendarPermission | "Allow $(PRODUCT_NAME) to access your calendar" | Only for: iOS 用于设置 |
remindersPermission | "Allow $(PRODUCT_NAME) to access your reminders" | Only for: iOS 用于设置 |
Are you using this library in an existing React Native app?
如果你没有使用 Continuous Native Generation(CNG)(你是手动使用原生 ios 项目),那么你需要在原生项目中配置以下权限:
-
对于 iOS,在项目的 ios/[app]/Info.plist 中添加
NSCalendarsUsageDescription和NSRemindersUsageDescription:<key>NSCalendarsUsageDescription</key> <string>Allow $(PRODUCT_NAME) to access your calendar</string> <key>NSRemindersUsageDescription</key> <string>Allow $(PRODUCT_NAME) to access your reminders</string>
用法
import * as Calendar from 'expo-calendar/next'; import { useEffect } from 'react'; import { StyleSheet, View, Text, Button } from 'react-native'; const BasicUsage = () => { useEffect(() => { (async () => { const { status } = await Calendar.requestCalendarPermissions(); if (status === 'granted') { const calendars = Calendar.getCalendars(Calendar.EntityTypes.EVENT); console.log('这里是你所有的日历:'); console.log(JSON.stringify(calendars)); } })(); }, []); return ( <View style={styles.container}> <Text>日历模块示例</Text> <Button title="创建一个新日历" onPress={createCalendar} /> </View> ); }; async function createCalendar() { const newCalendar = await Calendar.createCalendar({ title: 'Expo Calendar', color: 'blue', entityType: Calendar.EntityTypes.EVENT, }); console.log(`你的新日历:${JSON.stringify(newCalendar)}`); } const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#fff', alignItems: 'center', justifyContent: 'space-around', }, });
API
import * as Calendar from 'expo-calendar/next';
除非另有说明,所有日期都以 ISO 8601 格式返回。
启动系统提供的日历对话框
| Parameter | Type | Description |
|---|---|---|
| eventData(optional) | Omit<Partial<Event>, 'id'> | A map of details for the event to be created. Default: {} |
| presentationOptions(optional) | PresentationOptions | Configuration that influences how the calendar UI is presented. |
Launches the calendar UI provided by the OS to create a new event.
Promise<DialogEventResult>A promise which resolves with information about the dialog result.
| Parameter | Type |
|---|---|
| params | CalendarDialogParams |
| presentationOptions(optional) | OpenEventPresentationOptions |
Launches the calendar UI provided by the OS to preview an event.
Promise<OpenEventDialogResult>A promise which resolves with information about the dialog result.
Hooks
| Parameter | Type |
|---|---|
| options(optional) | PermissionHookOptions<object> |
Check or request permissions to access the calendar.
This uses both getCalendarPermissionsAsync and requestCalendarPermissionsAsync to interact
with the permissions.
[PermissionResponse | null, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]Example
const [status, requestPermission] = Calendar.useCalendarPermissions();
| Parameter | Type |
|---|---|
| options(optional) | PermissionHookOptions<object> |
Check or request permissions to access reminders.
This uses both getRemindersPermissionsAsync and requestRemindersPermissionsAsync to interact
with the permissions.
[PermissionResponse | null, RequestPermissionMethod<PermissionResponse>, GetPermissionMethod<PermissionResponse>]Example
const [status, requestPermission] = Calendar.useRemindersPermissions();
Classes
Type: Class extends ExpoCalendar
Represents a calendar object that can be accessed and modified using the Expo Calendar Next API.
This class provides properties and methods for interacting with a specific calendar on the device, such as retrieving its events, updating its details, and accessing its metadata.
ExpoCalendar Properties
CalendarAccessLevelLevel of access that the user has for the calendar.
AttendeeType[]Attendee types that this calendar supports.
booleanBoolean value that determines whether this calendar can be modified.
EntityTypesWhether the calendar is used in the Calendar or Reminders OS app.
booleanBoolean value indicating whether this is the device's primary calendar.
booleanIndicates whether this calendar is synced and its events stored on the device.
Unexpected behavior may occur if this is not set to true.
unionInternal system name of the calendar.
Acceptable values are: string | null
stringID of the source to be used for the calendar. Likely the same as the source for any other locally stored calendars.
ExpoCalendar Methods
| Parameter | Type |
|---|---|
| details | Partial<Omit<Event, 'creationDate' | 'lastModifiedDate' | 'originalStartDate' | 'isDetached' | 'status' | 'organizer'>> |
Creates a new event in the calendar.
Promise<ExpoCalendarEvent>An instance of the created event.
Creates a new reminder in the calendar.
Promise<ExpoCalendarReminder>An instance of the created reminder.
Deletes the calendar.
Promise<void>| Parameter | Type | Description |
|---|---|---|
| calendarId | string | The ID of the calendar to get. |
Gets a calendar by its ID. Throws an error if the calendar with the given ID does not exist.
Promise<ExpoCalendar>An ExpoCalendar object representing the calendar.
Returns a calendar event list for the given date range.
Promise<ExpoCalendarEvent[]>| Parameter | Type | Description |
|---|---|---|
| startDate(optional) | Date | null | Beginning of time period to search for reminders in, or Default: null |
| endDate(optional) | Date | null | End of time period to search for reminders in, or Default: null |
| status(optional) | ReminderStatus | null | One of Default: null |
Returns a list of reminders matching the provided criteria. If startDate and endDate are defined,
returns all reminders that overlap at all with the [startDate, endDate] interval, that is, all reminders
that end after the startDate or begin before the endDate.
Promise<ExpoCalendarReminder[]>An array of ExpoCalendarReminder objects matching the search criteria.
| Parameter | Type | Description |
|---|---|---|
| details | Partial<ModifiableCalendarProperties> | A map of properties to be updated. |
Updates the provided details of an existing calendar stored on the device. To remove a property,
explicitly set it to null in details.
Promise<void>Type: Class extends ExpoCalendarAttendee
Represents a calendar attendee object.
ExpoCalendarAttendee Properties
booleanIndicates whether or not this attendee is the current OS user.
ExpoCalendarAttendee Methods
Deletes the attendee.
Promise<void>Type: Class extends ExpoCalendarEvent
Represents a calendar event object that can be accessed and modified using the Expo Calendar Next API.
ExpoCalendarEvent Properties
unionDate when the event record was created.
Acceptable values are: string | Date
unionDate object or string representing the time when the event ends.
Acceptable values are: string | Date
booleanWhether invited guests can modify the details of the event.
stringFor instances of recurring events, volatile ID representing this instance. Not guaranteed to always refer to the same instance.
booleanBoolean value indicating whether or not the event is a detached (modified) instance of a recurring event.
unionDate when the event record was last modified.
Acceptable values are: string | Date
unionLocation field of the event.
Acceptable values are: string | null
OrganizerOrganizer of the event. This property is only available on events associated with calendars that are managed by a service such as Google Calendar or iCloud. The organizer is read-only and cannot be set.
stringFor detached (modified) instances of recurring events, the ID of the original recurring event.
unionFor recurring events, the start date for the first (original) instance of the event.
Acceptable values are: string | Date
unionObject representing rules for recurring or repeating events. Set to null for one-time events.
It is either endDate or occurrence based.
Acceptable values are: RecurrenceRule | null
unionDate object or string representing the time when the event starts.
Acceptable values are: string | Date
stringTime zone the event is scheduled in.
When set to null, the event is scheduled to the device's time zone.
ExpoCalendarEvent Methods
| Parameter | Type |
|---|---|
| attendee | Attendee |
Creates a new attendee and adds it to this event.
Promise<ExpoCalendarAttendee>Deletes the event.
Promise<void>| Parameter | Type |
|---|---|
| params(optional) | CalendarDialogParamsNext |
Launches the calendar UI provided by the OS to edit or delete an event.
Promise<DialogEventResult>A promise which resolves with information about the dialog result.
| Parameter | Type | Description |
|---|---|---|
| eventId | string | The ID of the event to get. |
Gets an event by its ID. Throws an error if the event with the given ID does not exist.
Promise<ExpoCalendarEvent>An ExpoCalendarEvent object representing the event.
Gets all attendees for a given event (or instance of a recurring event).
Promise<ExpoCalendarAttendee[]>An array of Attendee associated with the specified event.
| Parameter | Type | Description |
|---|---|---|
| recurringEventOptions(optional) | RecurringEventOptions | A map of options for recurring events. Default: {} |
Returns an event instance for a given event (or instance of a recurring event).
ExpoCalendarEventAn event instance.
| Parameter | Type |
|---|---|
| params(optional) | CalendarDialogOpenParamsNext |
Launches the calendar UI provided by the OS to preview an event.
Promise<OpenEventDialogResult>A promise which resolves with information about the dialog result.
| Parameter | Type | Description |
|---|---|---|
| details | Partial<ModifiableEventProperties> | A map of properties to be updated. |
Updates the provided details of an existing calendar stored on the device. To remove a property,
explicitly set it to null in details.
Promise<void>Type: Class extends ExpoCalendarReminder
Represents a calendar reminder object that can be accessed and modified using the Expo Calendar Next API.
ExpoCalendarReminder Properties
Alarm[]Array of Alarm objects which control automated alarms to the user about the task.
unionDate object or string representing the date of completion, if completed is true.
Setting this property of a nonnull Date will automatically set the reminder's completed value to true.
Acceptable values are: string | Date
unionDate when the reminder record was created.
Acceptable values are: string | Date
unionDate object or string representing the time when the reminder task is due.
Acceptable values are: string | Date
unionDate when the reminder record was last modified.
Acceptable values are: string | Date
unionObject representing rules for recurring or repeated reminders. null for one-time tasks.
Acceptable values are: RecurrenceRule | null
unionDate object or string representing the start date of the reminder task.
Acceptable values are: string | Date
ExpoCalendarReminder Methods
Deletes the reminder.
Promise<void>| Parameter | Type | Description |
|---|---|---|
| reminderId | string | The ID of the reminder to get. |
Gets a reminder by its ID. Throws an error if the reminder with the given ID does not exist.
Promise<ExpoCalendarReminder>An ExpoCalendarReminder object representing the reminder.
Methods
| Parameter | Type | Description |
|---|---|---|
| details(optional) | Partial<Calendar> | A map of details for the calendar to be created. Default: {} |
Creates a new calendar on the device, allowing events to be added later and displayed in the OS Calendar app.
Promise<ExpoCalendar>An ExpoCalendar object representing the newly created calendar.
Check or request permissions to access the calendar.
This uses both getCalendarPermissionsAsync and requestCalendarPermissionsAsync to interact
with the permissions.
Promise<PermissionResponse>Example
const [status, requestPermission] = Calendar.useCalendarPermissions();
| Parameter | Type |
|---|---|
| type(optional) | EntityTypes |
Gets an array of ExpoCalendar shared objects with details about the different calendars stored on the device.
Promise<ExpoCalendar[]>An array of ExpoCalendar shared objects matching the provided entity type (if provided).
Gets an instance of the default calendar object.
ExpoCalendarAn ExpoCalendar object that is the user's default calendar.
Checks user's permissions for accessing user's reminders.
Promise<PermissionResponse>Gets an array of Source objects with details about the different sources stored on the device.
Source[]| Parameter | Type | Description |
|---|---|---|
| calendars | (string | ExpoCalendar)[] | An array of calendar IDs ( |
| startDate | Date | The start date of the time range to search for events. |
| endDate | Date | The end date of the time range to search for events. |
Lists events from the device's calendar. It can be used to search events in multiple calendars.
Note: If you want to search events in a single calendar, you can use
ExpoCalendar.listEventsinstead.
Promise<ExpoCalendarEvent[]>An array of ExpoCalendarEvent objects representing the events found.
Asks the user to grant permissions for accessing user's calendars.
Promise<PermissionResponse>Asks the user to grant permissions for accessing user's reminders.
Promise<PermissionResponse>Types
A method for having the OS automatically remind the user about a calendar item.
| Property | Type | Description |
|---|---|---|
| absoluteDate(optional) | string | Only for: iOS Date object or string representing an absolute time the alarm should occur.
Overrides |
| method(optional) | AlarmMethod | Only for: Android Method of alerting the user that this alarm should use. On iOS this is always a notification. |
| relativeOffset(optional) | number | Number of minutes from the |
| structuredLocation(optional) | AlarmLocation | - |
| Property | Type | Description |
|---|---|---|
| coords(optional) | {
latitude: number,
longitude: number
} | - |
| proximity(optional) | string | - |
| radius(optional) | number | - |
| title(optional) | string | Only for: -iOS |
| Property | Type | Description |
|---|---|---|
| id | string | ID of the event to be presented in the calendar UI. |
| instanceStartDate(optional) | string | Date | Only for: iOS Date object representing the start time of the desired instance, if looking for a single instance of a recurring event. If this is not provided and id represents a recurring event, the first instance of that event will be returned by default. |
| Property | Type | Description |
|---|---|---|
| dayOfTheWeek | DayOfTheWeek | Sunday to Saturday - |
| weekNumber(optional) | number |
|
The result of presenting a calendar dialog for creating or editing an event.
| Property | Type | Description |
|---|---|---|
| action | Extract<CalendarDialogResultActions, 'done' | 'saved' | 'canceled' | 'deleted'> | How user responded to the dialog.
On Android, this is always On iOS, it can be |
| id | string | null | The ID of the event that was created or edited. On Android, this is always On iOS, this is a string when permissions are granted and user confirms the creation or editing of an event. Otherwise, it's |
Type: Pick<ExpoCalendar, 'color' | 'title'>
Type: Pick<ExpoCalendarEvent, 'title' | 'location' | 'timeZone' | 'url' | 'notes' | 'alarms' | 'recurrenceRule' | 'availability' | 'startDate' | 'endDate' | 'allDay'>
Type: Pick<ExpoCalendarReminder, 'title' | 'location' | 'timeZone' | 'url' | 'notes' | 'alarms' | 'recurrenceRule' | 'startDate' | 'dueDate' | 'completed' | 'completionDate'>
The result of presenting the calendar dialog for opening (viewing) an event.
| Property | Type | Description |
|---|---|---|
| action | Extract<CalendarDialogResultActions, 'done' | 'canceled' | 'deleted' | 'responded'> | Indicates how user responded to the dialog.
On Android, the |
Type: PresentationOptions extended by:
| Property | Type | Description |
|---|---|---|
| allowsCalendarPreview(optional) | boolean | Only for: iOS Determines whether event can be shown in calendar day view preview. This property applies only to invitations. Default: false |
| allowsEditing(optional) | boolean | Only for: iOS Whether to allow the user to edit the previewed event. This property applies only to events in calendars created by the user. Note that if the user edits the event, the returned action is the one that user performs last.
For example, when user previews the event, confirms some edits and finally dismisses the dialog, the event is edited, but response is Default: false |
Literal Type: union
Permission expiration time. Currently, all permissions are granted permanently.
Acceptable values are: 'never' | number
Literal Type: union
Acceptable values are: PermissionHookBehavior | Options
An object obtained by permissions get and request functions.
| Property | Type | Description |
|---|---|---|
| canAskAgain | boolean | Indicates if user can be asked again for specific permission. If not, one should be directed to the Settings app in order to enable/disable the permission. |
| expires | PermissionExpiration | Determines time when the permission expires. |
| granted | boolean | A convenience boolean that indicates if the permission is granted. |
| status | PermissionStatus | Determines the status of the permission. |
| Property | Type | Description |
|---|---|---|
| startNewActivityTask(optional) | boolean | Only for: Android Whether to launch the Activity as a new task.
If Default: true |
A recurrence rule for events or reminders, allowing the same calendar item to recur multiple times. This type is based on the iOS interface which is in turn based on the iCal RFC so you can refer to those to learn more about this potentially complex interface.
Not all the combinations make sense. For example, when frequency is DAILY, setting daysOfTheMonth makes no sense.
| Property | Type | Description |
|---|---|---|
| daysOfTheMonth(optional) | number[] | Only for: iOS The days of the month this event occurs on.
|
| daysOfTheWeek(optional) | DaysOfTheWeek[] | Only for: iOS The days of the week the event should recur on. An array of |
| daysOfTheYear(optional) | number[] | Only for: iOS The days of the year this event occurs on.
|
| endDate(optional) | string | Date | Date on which the calendar item should stop recurring; overrides |
| frequency | Frequency | How often the calendar item should recur. |
| interval(optional) | number | Interval at which the calendar item should recur. For example, an Default: 1 |
| monthsOfTheYear(optional) | MonthOfTheYear[] | Only for: iOS The months this event occurs on.
This field is only valid for |
| occurrence(optional) | number | Number of times the calendar item should recur before stopping. |
| setPositions(optional) | number[] | Only for: iOS TAn array of numbers that filters which recurrences to include. For example, for an event that
recurs every Monday, passing 2 here will make it recur every other Monday.
|
| weeksOfTheYear(optional) | number[] | Only for: iOS The weeks of the year this event occurs on.
|
Options for specifying a particular instance of a recurring event. This type is used in various methods that operate on recurring events, such as updating or deleting a single occurrence or a set of future occurrences.
| Property | Type | Description |
|---|---|---|
| futureEvents(optional) | boolean | Whether future events in the recurring series should also be updated. If |
| instanceStartDate(optional) | string | Date | Date object representing the start time of the desired instance, if looking for a single instance of a recurring event. If this is not provided and id represents a recurring event, the first instance of that event will be returned by default. |
A source account that owns a particular calendar. Expo apps will typically not need to interact with Source objects.
| Property | Type | Description |
|---|---|---|
| id(optional) | string | Only for: iOS Internal ID that represents this source on the device. |
| isLocalAccount(optional) | boolean | Only for: Android Whether this source is the local phone account. Must be |
| name | string | Name for the account that owns this calendar and was used to sync the calendar to the device. |
| type | string | SourceType | Type of the account that owns this calendar and was used to sync it to the device.
If |
Enums
Enum containing all possible user responses to the calendar UI dialogs. Depending on what dialog is presented, a subset of the values applies.
CalendarDialogResultActions.canceled = "canceled"The user canceled or dismissed the dialog.
CalendarDialogResultActions.done = "done"On Android, this is the only possible result because the OS doesn't provide enough information to determine the user's action - the user may have canceled the dialog, modified the event, or deleted it.
On iOS, this means the user simply closed the dialog.
CalendarDialogResultActions.responded = "responded"The user responded to and saved a pending event invitation.
权限
Android
如果你只打算使用 系统提供的日历 UI,则不需要请求任何权限。
否则,你必须将以下权限添加到 app.json 中的 expo.android.permissions 数组里。
| Android Permission | Description |
|---|---|
Allows an application to read the user's calendar data. | |
Allows an application to write the user's calendar data. |
iOS
如果你只打算使用系统提供的日历 UI,通过 createEventInCalendarAsync 创建事件,则不需要请求权限。
本库使用以下用途说明键: