需要引入 #import <EventKit/EventKit.h>
Privacy - Calendars Usage Description App需要您的同意,才能访问日历
Privacy - Reminders Usage Description App需要您的同意,才能访问提醒事项
//
// EventCalendar.h
// app添加到手机日历提醒事件
//
// Created by 郝晓博 on 16/12/27.
// Copyright © 2018年 郝晓博. All rights reserved.
//
#import <Foundation/Foundation.h>
@interface EventCalendar : NSObject
+ (instancetype)sharedEventCalendar;
/**
* 将App事件添加到系统日历提醒事项,实现闹铃提醒的功能
*
* @param title 事件标题
* @param location 事件位置
* @param startDate 开始时间
* @param endDate 结束时间
* @param allDay 是否全天
* @param alarmArray 闹钟集合
*/
- (void)createEventCalendarTitle:(NSString *)title location:(NSString *)location startDate:(NSDate *)startDate endDate:(NSDate *)endDate allDay:(BOOL)allDay alarmArray:(NSArray *)alarmArray;
@end
//
// EventCalendar.m
// app添加到手机日历提醒事件
//
// Created by 刘燕鲁 on 16/12/27.
// Copyright © 2016年 刘燕鲁. All rights reserved.
//
#import "EventCalendar.h"
#import <EventKit/EventKit.h>
#import <UIKit/UIKit.h>
@implementation EventCalendar
static EventCalendar *calendar;
+ (instancetype)sharedEventCalendar{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
calendar = [[EventCalendar alloc] init];
});
return calendar;
}
+(instancetype)allocWithZone:(struct _NSZone *)zone{
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
calendar = [super allocWithZone:zone];
});
return calendar;
}
- (void)createEventCalendarTitle:(NSString *)title location:(NSString *)location startDate:(NSDate *)startDate endDate:(NSDate *)endDate allDay:(BOOL)allDay alarmArray:(NSArray *)alarmArray{
__weak typeof(self) weakSelf = self;
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(), ^{
__strong typeof(weakSelf) strongSelf = weakSelf;
if (error)
{
[strongSelf showAlert:@"添加失败,请稍后重试"];
}else if (!granted){
[strongSelf showAlert:@"不允许使用日历,请在设置中允许此App使用日历"];
}else{
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = title;
event.location = location;
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];
event.startDate = startDate;
event.endDate = endDate;
event.allDay = allDay;
//添加提醒
if (alarmArray && alarmArray.count > 0) {
for (NSString *timeString in alarmArray) {
[event addAlarm:[EKAlarm alarmWithRelativeOffset:[timeString integerValue]]];
}
}
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
[strongSelf showAlert:@"已添加到系统日历中"];
}
});
}];
}
}
- (void)showAlert:(NSString *)message
{
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
[alert show];
}
@end