Programmatically add custom event in the iPhone calendar
One can use EventKit.framework to programmatically add custom event and add alarm to created events in iPhone calendarfrom within their apps. In this post, we will learn to create event in iPhone calendar programmatically from our IOS app.
First add EventKit.framework to your project as shown in below
Add custom event in default calendar app from our own app:
Import the eventkit framework in your file where you want to add event in iPhone calendar programmatically.
#import
Create an instance of EKEventStore class and an NSMutableArray to store all calendars created by user in his Calendar app on the iPhone.
NSMutableArray *calendarArray;
Get all calendars from the default calendar app on use iPhone/iPad
EKCalendar *currentCalendar = [allCalendars objectAtIndex:i];
Create event on default calendar app of iPhone/iPad
for (EKCalendar *cal in calendarArray)
{
{
break;
}
index = index+1;
}
if (index==[calendarArray count])
{
index =0;
}
EKCalendar *selectedCal;
{
selectedCal = [calendarArray objectAtIndex:index];
}
Adding event
EKEvent *event = [EKEvent eventWithEventStore:store];
event.calendar = selectedCal;
event.startDate = [NSDate date];
// 1 hour event only
NSDate *eventEndDate = [[NSDate alloc]initWithTimeInterval:3600 sinceDate:event.startDate];
event.endDate = eventEndDate;
[event addAlarm:alarm];
NSError *error;
{
}
else
{
}
Finally we save the event and if succeed in creating it, will save event identifier in user defaults so that we can delete it later if user save it again. Below is the code to delete event
if ([[NSUserDefaults standardUserDefaults]integerForKey:@”SavedEvent”] == 1)
{
NSString *eventIdentifier =[[NSUserDefaults standardUserDefaults] valueForKey:@”EventID”];
EKEvent *event = [store eventWithIdentifier:eventIdentifier];
NSError *error;
NSLog(@”%@”, [error localizedDescription]);
}
else {
NSLog(@”Event deleted successfully”);
}
Complete Code:
-(void)createEvent
{
int index =0 ;
for (EKCalendar *cal in calendarArray)
{
if ([cal.title isEqualToString:USER_CALENDAR_SELECTION])
{
break;
}
index = index+1;
}
if (index==[calendarArray count])
{
index =0;
}
EKCalendar *selectedCal;
{
selectedCal = [calendarArray objectAtIndex:index];
}
{
NSString *eventIdentifier =[[NSUserDefaults standardUserDefaults] valueForKey:@”EventID”];
EKEvent *event = [store eventWithIdentifier:eventIdentifier];
NSError *error;
{
NSLog(@”%@”, [error localizedDescription]);
}
else
{
}
}
EKEvent *event = [EKEvent eventWithEventStore:store];
event.calendar = selectedCal;
event.startDate = [NSDate date];
NSDate *eventEndDate = [[NSDate alloc]initWithTimeInterval:3600 sinceDate:event.startDate];
event.endDate = eventEndDate;
[event addAlarm:alarm];
NSError *error;
{
}
else
{
}
}