1.需要在info.plist添加访问日历的权限:Privacy - Calendars Usage Description
2.事件添加
新增事件
#import <EventKit/EKEventStore.h>
#import <EventKit/EKEvent.h>
#import <EventKit/EKAlarm.h>
-(void)createWithTitle:(NSString *)title
location:(NSString *)location
star:(NSDate *)star
end:(NSDate *)end
allday:(BOOL)all
alarms:(NSArray *)alarms
{
EKEventStore *evenstore = [[EKEventStore alloc]init];
if ([evenstore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) {
[evenstore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError * _Nullable error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error) {
NSLog(@"error : %@",error);
} else if (!granted) {
NSLog(@"未有日历访问权限");
} else {
EKEvent *event = [EKEvent eventWithEventStore:evenstore];
event.title = title;
event.location = location;
NSDateFormatter *tempformatter = [[NSDateFormatter alloc]init];
[tempformatter setDateFormat:@"dd.MM.yyyy HH:mm"];
event.startDate = star;
event.endDate = end;
event.allDay = all;
if (alarms.count>0) {
for (NSString *timestring in alarms) {
[event addAlarm:[EKAlarm alarmWithRelativeOffset:timestring.integerValue]];
}
}
[event setCalendar:[evenstore defaultCalendarForNewEvents]];
NSError *err;
[evenstore saveEvent:event span:EKSpanThisEvent error:&err];
NSLog(@"添加事件 error : %@",err);
}
});
}];
}
}
2.事件编辑操作
根据日期删除已存在的事件
-(void)deleteEventWithStar:(NSDate *)star
end:(NSDate *)end
{
EKEventStore *evenstore = [[EKEventStore alloc]init];
NSArray <EKCalendar*> *calendars = [evenstore calendarsForEntityType:EKEntityTypeEvent];
NSLog(@"calendars : %@",calendars);
if (calendars.count<=0) {
NSLog(@"no calendar here...");
return;
}
NSPredicate *predicate = [evenstore predicateForEventsWithStartDate:star endDate:end calendars:calendars];
NSArray <EKEvent *> *events = [evenstore eventsMatchingPredicate:predicate];
NSLog(@"events : %@",events);
if (events.count<=0) {
NSLog(@"no event here...");
return;
}
for (EKEvent *event in events) {
NSError *removeErr;
[evenstore removeEvent:event span:EKSpanThisEvent error:&removeErr];
NSLog(@"remove event err : %@",removeErr);
}
}
3.使用
增加提醒事件
-(void)addEvent
{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate *stardate = [formatter dateFromString:@"2021-02-20 08:00"];
NSDate *enddate = [formatter dateFromString:@"2021-02-20 08:01"];
[[Events shareEvents] createWithTitle:@"测试-------还款提醒" location:@"到期还款" star:stardate end:enddate allday:NO alarms:@[@"-120"]];
}
删除某段时间的提醒事件
-(void)deleteEvents
{
NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
[formatter setDateFormat:@"yyyy-MM-dd HH:mm"];
NSDate *stardate = [formatter dateFromString:@"2021-02-20 08:00"];
NSDate *enddate = [formatter dateFromString:@"2021-02-20 08:01"];
[[Events shareEvents]deleteEventWithStar:stardate end:enddate];
}