话不多说直接来
一、权限的获取
Privacy - Calendars Usage Description 是否允许此App使用日历?
Privacy - Reminders Usage Description 是否允许此App访问提醒事项?
更多权限获取:https://www.jianshu.com/p/31ef0f8ba34e
二、手动写入日历日程-代码部分
// 导入EventKit 库
#import <EventKit/EventKit.h>
// 先来一波权限判断
- (void)saveCalendar {
EKEventStore *eventStore = [[EKEventStore alloc] init];
__weak typeof(self) weakSelf = self;
//06.07 使用 requestAccessToEntityType:completion: 方法请求使用用户的日历数据库
if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) {
// 获取访问权限
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (error)
{
//报错啦
}
else if (!granted)
{
// 被用户拒绝,不允许访问日历,滚去开启权限
}
else
{
dispatch_async(dispatch_get_main_queue(), ^{
// 用户既然允许事件保存到日历,那就去保存吧
[weakSelf saveDataCalendar:eventStore];
});
}
}];
}
}
// 写入日历
- (void)saveDataCalendar:(EKEventStore *)eventStore {
// 创建事件
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
// 这里拿当前时间 (自己写的话格式最好用 yyyy/MM/dd hh:mmaaa)
NSDate *date = [NSDate date];
event.title = @"事件标题标标标" ; // 事件标题
event.location = @"事件地点地地地地" ; // 事件地点
event.notes = @"事件备注备备备"; // 事件备注
event.startDate = [date dateByAddingTimeInterval:60 * 2]; // 开始时间
event.endDate = [date dateByAddingTimeInterval:60 * 30]; // 结束时间
//第一次提醒 (几分钟后)
[event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -5.0f]];
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
}
三、利用系统界面写入日历日程-代码部分
// 导入EventKit和EventKitUI 库
#import <EventKit/EventKit.h>
#import <EventKitUI/EventKitUI.h>
- (void) saveCalendar {
EKEventStore *eventStore = [[EKEventStore alloc]init];
if([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) {
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted,NSError* error){
if(!granted){
dispatch_async(dispatch_get_main_queue(), ^{
//TODO: 提示需要权限
});
}else{
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = @"日历标题";
EKCalendar* calendar;
calendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:eventStore];
NSError* error;
[eventStore saveCalendar:calendar commit:YES error:&error];
EKEventEditViewController *addController = [[EKEventEditViewController alloc] initWithNibName:nil bundle:nil];
addController.event = event;
addController.eventStore = eventStore;
[self presentViewController:addController animated:YES completion:nil];
addController.editViewDelegate = self;
}
}];
}
}
#pragma mark - eventEditDelegates -
- (void)eventEditViewController:(EKEventEditViewController *)controller didCompleteWithAction:(EKEventEditViewAction)action{
if (action ==EKEventEditViewActionCanceled) {
[self dismissViewControllerAnimated:YES completion:nil];
}
if (action==EKEventEditViewActionSaved) {
[self dismissViewControllerAnimated:YES completion:nil];
}
}
QQ20190701-134823-HD-2.gif
测试Demo
网友评论