iOS开发--事件保存到系统日历

 系统库:EventKit
- (void)saveEventToCalendar
{
EKEventStore *eventStore = [[EKEventStore alloc] init];
if ([eventStore  respondsToSelector:@selector(requestAccessToEntityType:completion:)]){
  [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error)
            {
                //错误信息
                
            }
            else if (!granted)
            {
                //被用户拒绝,不允许访问日历
               
            }
            else
            {

                NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
                [dateFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
                NSDate *date = [NSDate date];
                // 先判断是否添加了事件
                NSDate *startDate =[date dateByAddingTimeInterval:60 * 3];
                NSDate *endDate =[date dateByAddingTimeInterval:60 * 5];

                NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:startDate endDate:endDate calendars:@[[eventStore defaultCalendarForNewEvents]]];
                NSArray *events = [eventStore eventsMatchingPredicate:predicate];

                for (EKEvent *event in events) {
                    if([event.title  isEqualToString:[NSString stringWithFormat:@"%@%@",@"name",EVENT_TITLE]] &&
                       [event.location isEqualToString:EVENT_LOCATION]){
                        // 说明提醒事件存在
                        NSLog(@"事件已存在");
                        return ;

                    }
                }
                //事件保存到日历
                EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
                event.title = [NSString stringWithFormat:@"%@",EVENT_TITLE];
                event.location = EVENT_LOCATION;
                event.startDate = startDate;
                event.endDate   = endDate;
                //添加提醒
                [event addAlarm:[EKAlarm alarmWithRelativeOffset:-(60.0f * 1.0f)]];
                [event addAlarm:[EKAlarm alarmWithRelativeOffset:-(60.0f * 2.0f)]];
                [event setCalendar:[eventStore defaultCalendarForNewEvents]];
                NSError *err;
                [eventStore saveEvent:event span:EKSpanThisEvent error:&err];
                UIAlertView *alert = [[UIAlertView alloc]
                                      initWithTitle:@"提醒成功"
                                      message:@"系统将会在***开始2分钟前提醒您"
                                      delegate:nil
                                      cancelButtonTitle:@"确定"
                                      otherButtonTitles:nil];
                [alert show];
            }
            });
        }];
}

}

参考文章:https://www.cnblogs.com/xiaobaichangan/p/5160025.html

你可能感兴趣的:(iOS开发--事件保存到系统日历)