Sunday, 17 April 2016

How to Programmatically add custom event in the iPhone Calendar - Tutorial


Programmatically create event in iPhone calendar in IOS sdk

Introduction How to Programmatically add custom event in the iPhone Calendar

One can use EventKit.framework to create events and add alarm to created events in iPhone calendar from 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

Adding framework in Xcode

  Writing code to add event in default calendar app from our own app:

Import the 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.


   EKEventStore *store;
   NSMutableArray *calendarArray;

Get all calendars from the default calendar app on use iPhone/iPad

In first step, we will get all calendars created by user in his iPhone's calendar app (in my case i have to set event in calendar chosen by user inside the app). Below is the code for getting calendars


-(void)getAllCalendars
{
    calendarArray = [[NSMutableArray alloc]initWithCapacity:0];
    store = [[EKEventStore alloc]init];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)    {
        if (error == nil) {
            // Store the returned granted value.
            calendarArray = (NSMutableArray *)[self getLocalCalendars];
            
        }
        else{
            // In case of error, just log its description to the debugger.
            NSLog(@"%@", [error localizedDescription]);
        }
    }];

}

-(NSArray *)getLocalCalendars
{
    
    NSArray *allCalendars = [store calendarsForEntityType:EKEntityTypeEvent];
    NSMutableArray *localCalendars = [[NSMutableArray alloc] init];
    
    for (int i=0; i< [allCalendars count]; i++) {        
 EKCalendar *currentCalendar = [allCalendars objectAtIndex:i];
        if (currentCalendar.allowsContentModifications)
        {
            [localCalendars addObject:currentCalendar];
        }
    }
    return (NSArray *)localCalendars;
}


In above code, we initialize our NSMutableArray instance calendarArray and EKEventStore instance store. Then we request user to allow access to calendar app in order to save events in it. In getLocalCalendars method we will only add those calendars whose content modification is set to yes.

Create event on default calendar app of iPhone/iPad

At this moment, we have all calendars from Calendar App with us in an array. It's time to create an event. Now, we will select calendar as per our user selection in settings screen of the app.


    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;
    if ([calendarArray count]!=0)
    {
        
        selectedCal = [calendarArray objectAtIndex:index];
    }


We have our selected calendar with us and if there is no match then we add event to default calendar.
Let us add event to calendar, below is the code for creating event with 1 hour duration


 // Create a new event object.
 EKEvent *event = [EKEvent eventWithEventStore:store];
 // Set the event title.
 event.title = @"Event Tittle";
 // Set its calendar.
 event.calendar = selectedCal;
 event.startDate = [NSDate date];
 // 1 hour event only
 NSDate *eventEndDate = [[NSDate alloc]initWithTimeInterval:3600 sinceDate:event.startDate];
 event.endDate = eventEndDate;


 EKAlarm *alarm = [EKAlarm alarmWithAbsoluteDate:[NSDate dateWithTimeInterval:-3600 sinceDate:event.startDate]];           
 // Add the alarm to the event.
 [event addAlarm:alarm];


                
 // Save and commit the event.
 NSError *error;
    if ([store saveEvent:event span:EKSpanFutureEvents commit:YES error:&error])
    {
          //success
        [[NSUserDefaults standardUserDefaults]setValue:event.eventIdentifier forKey:@"EventID"];
        [[NSUserDefaults standardUserDefaults]setInteger:1 forKey:@"SavedEvent"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        
    }
    else
    {
        // An error occurred, so log the error description.
        NSLog(@"%@", [error localizedDescription]);
    }
    

In above code, we create an instance of EKEvent class with respect to EKEventStore. Set tittle for event, set calendar in which we want to set this event, set its start date and its end date. Set alarm to event.
        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];
        
        // Delete it.
         NSError *error;
         if (![store removeEvent:event span:EKSpanFutureEvents error:&error]) {
         // Display the error description.
            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;
    if ([calendarArray count]!=0)
    {
        
        selectedCal = [calendarArray objectAtIndex:index];
    }
    
    if ([[NSUserDefaults standardUserDefaults]integerForKey:@"SavedEvent"] == 1)
    {
        NSString *eventIdentifier =[[NSUserDefaults standardUserDefaults] valueForKey:@"EventID"];
                                    
        EKEvent *event = [store eventWithIdentifier:eventIdentifier];
                                    
        // Delete it.
        NSError *error;
        if (![store removeEvent:event span:EKSpanFutureEvents error:&error])
        {
            // Display the error description.
            NSLog(@"%@", [error localizedDescription]);
        }
        else
        {
            NSLog(@"Event deleted successfully");
        }
    }
    
    // Create a new event object.
    EKEvent *event = [EKEvent eventWithEventStore:store];
    // Set the event title.
    event.title = @"Event Tittle";
    // Set its calendar.
    event.calendar = selectedCal;
    event.startDate = [NSDate date];
    // 1 hour event only
    NSDate *eventEndDate = [[NSDate alloc]initWithTimeInterval:3600 sinceDate:event.startDate];
    event.endDate = eventEndDate;


EKAlarm *alarm = [EKAlarm alarmWithAbsoluteDate:[NSDate dateWithTimeInterval:-3600 sinceDate:event.startDate]];           
 // Add the alarm to the event.
 [event addAlarm:alarm];


    // Save and commit the event.
    NSError *error;
    if ([store saveEvent:event span:EKSpanFutureEvents commit:YES error:&error])
    {
        //success
        [[NSUserDefaults standardUserDefaults]setValue:event.eventIdentifier forKey:@"EventID"];
        [[NSUserDefaults standardUserDefaults]setInteger:1 forKey:@"SavedEvent"];
        [[NSUserDefaults standardUserDefaults]synchronize];
        
    }
    else
    {
        // An error occurred, so log the error description.
        NSLog(@"%@", [error localizedDescription]);
    }
    

}

Final Output

You will see event in calendar as shown below

Event in iPhone's Calendar App

Event in iPhone's Calendar App - Detail

Where to go from here: 

In this post you learn How to Programmatically add custom event in the iPhone Calendar app. If you have any questions then feel free to ask. Happy Coding :)

No comments:
Write comments