首页 > 解决方案 > 使用日历 API 将事件插入默认日历

问题描述

react-native看来我无法使用和exposdk将事件插入设备上的默认日历中。我试过这个:

import * as Permissions from 'expo-permissions';
import * as Calendar from 'expo-calendar';
import { Platform } from 'react-native';
...

async obtainDefaultCalendarId() {
    let calendar = null;
    if (Platform.OS === 'ios') {
      calendar = await Calendar.getDefaultCalendarAsync();
    } else {
      const calendars = await Calendar.getCalendarsAsync();
      calendar = calendars
        ? calendars.find((cal) => cal.isPrimary) || calendars[0]
        : null;
    }
    return calendar ? calendar.id.toString() : null;
  }

  async obtainCalendarPermission() {
    let permission = await Permissions.getAsync(Permissions.CALENDAR);
    if (permission.status !== 'granted') {
      permission = await Permissions.askAsync(Permissions.CALENDAR);
      if (permission.status !== 'granted') {
        Alert.alert('Permission not granted to access the calendar');
      }
    }
    return permission;
  }

  async addReservationToCalendar(date) {
    await this.obtainCalendarPermission();
    CalendarId = this.obtainDefaultCalendarId();
    const startDate = new Date(Date.parse(date));
    const endDate = new Date(Date.parse(date) + 2 * 60 * 60 * 1000);
    Calendar.createEventAsync(CalendarId, {
      title: 'Con Fusion Table Reservation',
      location:
        '121, Clear Water Bay Road, Clear Water Bay, Kowloon, Hong Kong',
      startDate: startDate,
      endDate: endDate,
      timeZone: 'Asia/Hong_Kong',
    });
    Alert.alert('Reservation has been added to your calendar');
  }
...

它要求获得许可,但没有将事件添加到我的日历中。在我的屏幕上看到任何错误之前,expo 客户端应用程序已被粉碎。

图片


我没有得到错误发生的位置。当我 console.log(CalendarId) 时,我得到了这个,

Promise {
  "_40": 0,
  "_55": null,
  "_65": 0,
  "_72": null,
}

如果有人帮助我解决这个问题,我衷心感谢。

标签: react-nativeexpo

解决方案


const newCalendarID = await Calendar.createEventAsync(
   calendar.id, {
       ... 
   }
);

推荐阅读