Programmatically add custom event in the iPhone Calendar
Solution 1
Based on Apple Documentation, this has changed a bit as of iOS 6.0.
1) You should request access to the user's calendar via "requestAccessToEntityType:completion:" and execute the event handling inside of a block.
2) You need to commit your event now or pass the "commit" param to your save/remove call
Everything else stays the same...
Add the EventKit framework and #import <EventKit/EventKit.h>
to your code.
In my example, I have a NSString *savedEventId instance property.
To add an event:
EKEventStore *store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) { return; }
EKEvent *event = [EKEvent eventWithEventStore:store];
event.title = @"Event Title";
event.startDate = [NSDate date]; //today
event.endDate = [event.startDate dateByAddingTimeInterval:60*60]; //set 1 hour meeting
event.calendar = [store defaultCalendarForNewEvents];
NSError *err = nil;
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
self.savedEventId = event.eventIdentifier; //save the event id if you want to access this later
}];
Remove the event:
EKEventStore* store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) { return; }
EKEvent* eventToRemove = [store eventWithIdentifier:self.savedEventId];
if (eventToRemove) {
NSError* error = nil;
[store removeEvent:eventToRemove span:EKSpanThisEvent commit:YES error:&error];
}
}];
This adds events to your default calendar, if you have multiple calendars then you'll have find out which one that is
Swift version
You need to import the EventKit framework
import EventKit
Add event
let store = EKEventStore()
store.requestAccessToEntityType(.Event) {(granted, error) in
if !granted { return }
var event = EKEvent(eventStore: store)
event.title = "Event Title"
event.startDate = NSDate() //today
event.endDate = event.startDate.dateByAddingTimeInterval(60*60) //1 hour long meeting
event.calendar = store.defaultCalendarForNewEvents
do {
try store.saveEvent(event, span: .ThisEvent, commit: true)
self.savedEventId = event.eventIdentifier //save event id to access this particular event later
} catch {
// Display error to user
}
}
Remove event
let store = EKEventStore()
store.requestAccessToEntityType(EKEntityTypeEvent) {(granted, error) in
if !granted { return }
let eventToRemove = store.eventWithIdentifier(self.savedEventId)
if eventToRemove != nil {
do {
try store.removeEvent(eventToRemove, span: .ThisEvent, commit: true)
} catch {
// Display error to user
}
}
}
Solution 2
You can do this using the Event Kit framework in OS 4.0.
Right click on the FrameWorks group in the Groups and Files Navigator on the left of the window. Select 'Add' then 'Existing FrameWorks' then 'EventKit.Framework'.
Then you should be able to add events with code like this:
#import "EventTestViewController.h"
#import <EventKit/EventKit.h>
@implementation EventTestViewController
- (void)viewDidLoad {
[super viewDidLoad];
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = @"EVENT TITLE";
event.startDate = [[NSDate alloc] init];
event.endDate = [[NSDate alloc] initWithTimeInterval:600 sinceDate:event.startDate];
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
}
@end
Solution 3
Yes there still is no API for this (2.1). But it seemed like at WWDC a lot of people were already interested in the functionality (including myself) and the recommendation was to go to the below site and create a feature request for this. If there is enough of an interest, they might end up moving the ICal.framework to the public SDK.
https://developer.apple.com/bugreporter/
Solution 4
Calendar access is being added in iPhone OS 4.0:
Calendar Access
Apps can now create and edit events directly in the Calendar app with Event Kit.
Create recurring events, set up start and end times and assign them to any calendar on the device.
Solution 5
Swift 4.0 implementation :
use import in top of page by import EventKit
then
@IBAction func addtoCalendarClicked(sender: AnyObject) {
let eventStore = EKEventStore()
eventStore.requestAccess( to: EKEntityType.event, completion:{(granted, error) in
if (granted) && (error == nil) {
print("granted \(granted)")
print("error \(error)")
let event = EKEvent(eventStore: eventStore)
event.title = "Event Title"
event.startDate = Date()
event.endDate = Date()
event.notes = "Event Details Here"
event.calendar = eventStore.defaultCalendarForNewEvents
var event_id = ""
do {
try eventStore.save(event, span: .thisEvent)
event_id = event.eventIdentifier
}
catch let error as NSError {
print("json error: \(error.localizedDescription)")
}
if(event_id != ""){
print("event added !")
}
}
})
}
Related videos on Youtube
Comments
-
Vadim about 4 years
Is there any way to add iCal event to the iPhone Calendar from the custom App?
-
David Carney almost 14 yearsThanks for posting this. Just a reminder to all who read this: take care to watch for memory leaks. There are a couple in this code sample. Also, best practices would dictate that you check the value of 'err' after saveEvent:span:error and handle things accordingly.
-
Jay Vachhani almost 14 yearsDo you know how to add recurrence event? like an event for every monday?
-
DenTheMan over 13 yearsAdd recurrence event programmatically: check this out developer.apple.com/library/ios/#documentation/EventKit/…. Another option is to use the default framework-supplied view controllers for adding/editing events (like the Calendar At-A-Glance app bit.ly/cJq4Bh). For this option, see developer.apple.com/library/ios/#documentation/EventKitUI/…
-
Nate over 13 yearsTo add frameworks in XCode 4 see this SO question: stackoverflow.com/questions/3352664/…
-
Rajesh_Bangalore almost 12 years
-
coder1010 over 11 yearsCan Tapku Library calendar synchronise with calender app events
-
Rajesh_Bangalore over 11 yearsAll i know is that Tapku library is a calendar component control which has an option called Data source. So its upto ur logic to write the where that source you are fetching from... Happy Coding :)
-
Jasper about 11 yearsanswer is outdated, consider to remove this
-
Boris Gafurov over 10 yearsdoes not work for me, everything goes w/o errors but no event in calendar
-
Boris Gafurov over 10 years4.0? not gonna fly in 6 see above answer
-
Admin over 10 yearsEverything is storing in ekevent object but not storing inside the calendar hlp me
-
Ans about 10 years@William T: Can I present Add Event screen of Calendar app (using URL Scheme) and pass event's info so that when Add Event screen appear, it will have pre filled data. User just need to press add event button. In your example event added without any indication to user.
-
zonabi about 10 yearsif all seems to work yet no calendar appears, check to see if Cloud VS Local calendars is the issue. If you have a mix of Cloud and Local Calendars, Cloud calendars can force the local calendars to become hidden.
-
Logger over 9 years@William It is working for me. Here i am facing one problem if i add more than one events to the calendar and tried to remove event from the calendar, It is removing only last event from the calendar. How to get identifier for event when we are removing from the calendar.
-
William T. over 9 years@ReddyBasha when you add the event, you need to save off the eventIdentifier and store it for future use. You should use that event id when you go to remove it.
-
moody over 6 yearsAnd also remember that end date must be equal or bigger than the start date. Otherwise, you will get another error.
-
Dilip Tiwari over 6 yearscould u help me with google calendar regarding same answer @Dashrath