How to Programmatically Create new Calendars on iPhone that will sync to iCal - iphone

I'm looking for a way to create a new Calendar on the iphone device programatically. I have been looking at Event Kit and it clearly states how to create a new event in a calendar and there is also a convenient way of gathering all the calendars in code, What I can't find is how to create a new one that is saved to the device.
Any ideas'

Check this kal repository for creating programmatically iphone calendar same as iCal
Check this method for creating programmatically event:
-(void)initCalendar {
// An array of 1 dictionary object, containing START and END values.
NSMutableArray* pvDict = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:PV_URL ]];
// Check if the private view event already exists in the default calendar.
// Then set the calendar button state.
// Get a entry point to the Calendar database.
self.store = [[EKEventStore alloc ] init ];
// Get an array of all the calendars.
NSArray *calendars = store.calendars;
// Get the default calendar, set by the user in preferences.
EKCalendar *defaultCal = store.defaultCalendarForNewEvents;
// Find out if this calendar is modifiable.
BOOL isDefaultCalModifiable = defaultCal.allowsContentModifications ;
// Create an event in the default calendar.
self.event = [ EKEvent eventWithEventStore:store ];
self.event.title = CHELSEA_SPACE ;
self.event.location = CHELSEA_ADDRESS ;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyy-MM-dd HH:mm:ss.S"];
NSString *startString = [[ pvDict objectAtIndex:0] objectForKey:#"starts" ];
NSDate *dateStart = [dateFormatter dateFromString:startString];
NSString *endString = [[ pvDict objectAtIndex:0] objectForKey:#"ends" ];
NSDate *dateEnd = [dateFormatter dateFromString:endString];
self.event.startDate = dateStart;
self.event.endDate = dateEnd;
self.event.calendar = defaultCal ;
// Alternative code to add 2.5 hours to start time.
// [[NSDate alloc] initWithTimeInterval:9000 sinceDate:event.startDate];
// Search for events which match this date/time start and end.
// Compare the matched events by event TITLE.
NSPredicate *predicate = [store predicateForEventsWithStartDate:event.startDate
endDate:event.endDate calendars:calendars];
NSArray *matchingEvents = [store eventsMatchingPredicate:predicate];
self.calendarButton.enabled = NO;
if( ! isDefaultCalModifiable ) {
// The default calendar is not modifiable
return ;
}
if ( [ matchingEvents count ] > 0 ) {
// There are already event(s) which match this date/time start and end.
// Check if this event is the PV
EKEvent *anEvent;
int j;
for ( j=0; j < [ matchingEvents count]; j++) {
anEvent = [ matchingEvents objectAtIndex:j ] ;
if([ CHELSEA_SPACE isEqualToString: anEvent.title ]) {
// PV event already exists in calendar.
return;
}
}
[ anEvent release ];
}
self.calendarButton.enabled = YES;
[ pvDict release ];
}
-(void)addEventToCalendar:(id)sender {
NSError *error;
BOOL saved = [self.store saveEvent:self.event span:EKSpanThisEvent error:&error];
NSLog(#"Saved calendar event = %#\n", (saved ? #"YES" : #"NO"));
self.calendarButton.enabled = NO;
}

Related

iOS Search Calendar using title property

I am trying to make an app that permits the user to make events in one specified calendar.
The problem is that:
I can't find a solution to know if there's a calendar with the title that I want to use.
If the list is empty I write a code that creates the calendar but if the list isn't empty I need to know if there's a calendar with the calendar.title that I need.
If there isn't any calendar, I create the calendar; if there is I add the event to this calendar.
Below is the code I am using:
EKEvent *myEvent;
EKEventStore *store;
EKSource* localSource;
EKCalendar* newCal;
store = [[EKEventStore alloc] init];
myEvent = [EKEvent eventWithEventStore: store];
NSString* title = [arguments objectAtIndex:1];
NSString* location = [arguments objectAtIndex:2];
NSString* message = [arguments objectAtIndex:3];
NSString* startDate = [arguments objectAtIndex:4];
NSString* endDate = [arguments objectAtIndex:5];
NSString* calendarTitle = [arguments objectAtIndex:6];
//NSString* calID = nil;
//int i = 0;
EKCalendar* calendar = nil;
if(calendarTitle == nil){
calendar = store.defaultCalendarForNewEvents;
} else {
NSIndexSet* indexes = [store.calendars indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
*stop = false;
EKCalendar* cal = (EKCalendar*)obj;
if(cal.title == calendarTitle){
*stop = true;
}
return *stop;
}];
if (indexes.count == 0) {
//if list is empty i haven't calendars then i need to create it
for (EKSource* source in store.sources)
{
if (source.sourceType == EKSourceTypeLocal)
{
localSource = source;
break;
}
}
if (!localSource) return;
newCal = [EKCalendar calendarWithEventStore:store];
calendar.source = localSource;
calendar.title = calendarTitle;
NSError* error;
bool success = [store saveCalendar:newCal commit:YES error:&error];
if (error != nil)
{
NSLog(error.description);
}
//calendar created
} else {
//!Empty List i need to search the calendar with the title = calendarTitle
//And if there isn't i need to create it
//calendar = [store.calendars objectAtIndex:[indexes firstIndex]];
}
}
I think the problem is your implementation of indexesOfObjectsPassingTest. You're not returning any indexes, and since you try to stop it after it finds one index, you should just use the singular version indexOfObjectPassingTest. You can very simply write that like this:
NSUInteger* indx = [store.calendars indexOfObjectPassingTest:^BOOL(EkCalendar *cal, NSUInteger idx, BOOL *stop) {
return [cal.title isEqualToString:calendarTitle];
}];
Then, after checking to see that index is not NSNotFound use
calendar = store.calendars[indx];

iPhone - How to import native calendar events to my iphone app?

I am doing one simple application using iPhone calendar, where I need to import the iPhone native calendar events into my iPhone app. How can I do this. I have a piece of code but it doesn't seems to be working. I have added some events into my iPhone native calendar. But when i retrieve it's not fetching anything. Here is the piece of code.
-(IBAction)importCalEvents:(id)sender
{
NSArray *caleandarsArray = [[NSArray alloc] init];
caleandarsArray = [[eventStore calendars] retain];
NSLog(#"Calendars from Array : %#", caleandarsArray);
for (EKCalendar *CalendarEK in caleandarsArray)
{
NSLog(#"Calendar Title : %#", CalendarEK.title);
}
}
you can fetch all the calendar events like this.
import these 2 framworks (add if not exists into your project).
1 EventKit/EventKit.h
2) EventKitUI/EventKitUI.h
call this function on button click
-(void)EventList{
EKEventStore *eventStore = [[EKEventStore alloc] init];
NSDate *startDate = [[NSDate alloc] init];
NSDate *endDate = [[NSDate alloc] initWithTimeInterval:3600 sinceDate:startDate];
NSArray *calendars = [eventStore calendars];
NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:startDate
endDate:endDate calendars:calendars];
NSArray *matchingEvents = [eventStore eventsMatchingPredicate:predicate];
EKEvent *anEvent;
NSLog(#"Total Events >> %d",[matchingEvents count]);
for (int j=0; j < [ matchingEvents count]; j++) {
anEvent = [matchingEvents objectAtIndex:j];
NSLog(#"Title >>>%#",anEvent.title);
NSLog(#"start date is %# \n End Date is >>> %#",anEvent.startDate,anEvent.endDate);
}
}
And set the startDate and EndDate as per your Requirement.
so you can get all the detatils you want.
Best Luck..

Google calender event description retrieval in objective c [duplicate]

I am retrieving google calendar events using gdata library in objective c for an iphone application, I am doing it like this,
- (void)eventsTicket:(GDataServiceTicket *)ticket finishedWithEntries:(GDataFeedCalendarEvent *)feed error:(NSError *)error
{
if( !error ){
NSMutableDictionary *dictionary;
for( int section=0; section<[data count]; section++ ){
NSMutableDictionary *nextDictionary = [data objectAtIndex:section];
GDataServiceTicket *nextTicket = [nextDictionary objectForKey:KEY_TICKET];
if( nextTicket==ticket ){ // We've found the calendar these events are meant for...
dictionary = nextDictionary;
break;
}
}
if( !dictionary )
return; // This should never happen. It means we couldn't find the ticket it relates to.
int count = [[feed entries] count]; // count for the number of events for the callendar
//099999999999999999999999999999999966666666666666669999999999999999999999999666666666666666699999999999999999999999999999999999999999999999999999999999
daily_trackAppDelegate *controller =(daily_trackAppDelegate *) [[UIApplication sharedApplication] delegate];
NSMutableArray *events = [dictionary objectForKey:KEY_EVENTS];
for( int i=0; i<count; i++ ){
[events addObject:[[feed entries] objectAtIndex:i]]; //loads the array with events
}
for( int i=0; i<count; i++ ){
NSMutableArray *temporary=[[NSMutableArray alloc]init];
[temporary removeAllObjects];
GDataEntryCalendarEvent *event = [events objectAtIndex:i];
// [controller.googlearray addObject:event];
GDataWhen *when = [[event objectsForExtensionClass:[GDataWhen class]] objectAtIndex:0];
if( when ){
NSDate *date1 = [[when startTime] date];
NSDate *date = [date1 dateByAddingTimeInterval:18000.0];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yy-MM-dd-HH-mm"];
[temporary addObject:date];///1 date
NSDate *date11=[[when endTime] date];
NSDate *date2 = [date11 dateByAddingTimeInterval:18000.0];
// [controller.array_objject.google_events insertObject:date atIndex:i];///2 date
[temporary addObject:date2];///1 date
[dateFormatter release];
}
//[controller.array_objject.google_events insertObject:[[event title] stringValue] atIndex:i]; /////3 title
[temporary addObject:[[event title] stringValue]];///1 date
GDataWhere *addr = [[event locations] objectAtIndex:0];
if( addr )
//[controller.array_objject.google_events insertObject:[addr stringValue] atIndex:i];///// 4 location
[temporary addObject:[addr stringValue]];
[controller.googlearray addObject:temporary];///// 4 location
}
NSURL *nextURL = [[feed nextLink] URL];
if( nextURL ){ // There are more events in the calendar... Fetch again. FETCHING*********************************
GDataServiceTicket *newTicket = [googleCalendarService fetchFeedWithURL:nextURL delegate:self didFinishSelector:#selector( eventsTicket:finishedWithEntries:error: )]; // Right back here...
// Update the ticket in the dictionary for the next batch.
[dictionary setObject:newTicket forKey:KEY_TICKET];
}
} else
[self handleError:error];
}
now I am retrieving the start and ending time, title, location etc. of the event here, but I also want to retrieve the description of the event, means if user enters any description while creating event, so in that case I want to retrieve that description or details of event too, I tried hard but in vain.
The description of an event is available as [[eventEntry content] stringValue]

iPhone Event Kit : programmatically create a EKCalendar?

I would like to insert events in my app, so they can be viewed in iPhone Calendar.app. But since I don't want to mix the user events with those from my app, I wanted to create a EKCalendar like "MyApp Events"
Is this possible ? How would you filter your events otherwise ?
Thanks !
It is absolutely possible to create your own calendar - the catch is that you need iOS 5:
EKEventStore* eventStore = [[EKEventStore alloc] init];
NSString* calendarName = #"My Cal";
EKCalendar* calendar;
// Get the calendar source
EKSource* localSource;
for (EKSource* source in eventStore.sources) {
if (source.sourceType == EKSourceTypeLocal)
{
localSource = source;
break;
}
}
if (!localSource)
return;
calendar = [EKCalendar calendarWithEventStore:eventStore];
calendar.source = localSource;
calendar.title = calendarName;
NSError* error;
bool success= [eventStore saveCalendar:calendar commit:YES error:&error];
if (error != nil)
{
NSLog(error.description);
// TODO: error handling here
}
Do you (or anyone else) have any progress with adding a new Calendar?
I've got the same situation. I can programmatically add events to the default calendar perfectly well, but I'd like to add them to a new calendar, so they don't interfere with the users exsisting events, and can be easily deleted/hidden by the user instead of removing all events manually.
You can't set the properties for a new EKCalendar object. It looks like you can only assign an exsiting one like defaultCalendarForNewEvents to an EKCalendar object.
However, I know it's possible to programmatically create a new calendar, because I've seen iPhone app doing this (without leaving the app).
Could it be that they use a workaround by doing some trick with an external ICS file?
Maybe it is possible to do this by "subscribing" to a local (on the iPhone/app filesystem) generated ICS file, instead of an URL. Does anyone have any experience with this?
This is how you can check out whether a calendar already exists with specific title.
If it does not exists then you can create it programatically.
Declare a Boolean Type Variable
BOOL doesExist=NO;
EKEventStore *eventStore=[[EKEventStore alloc] init];
NSArray *calanders=[eventStore calendarsForEntityType:EKEntityTypeEvent];
//Now Iterate through every calendar in the array and match its title
// with the title that you want to create
for(EKCalendar calendar in calendars)
{
if([[calendar title] isEqualToString:#"youdesiredname"])
{
doesExist=YES;
}
}
// so now check if our bool variable contains value YES it means that a calendar with same name/title already exists.if no then you can create
if(!doesExist)
{
NSString* calendarName = #"DesiredCalendarName";
EKCalendar* calendar;
EKSource* localSource;
for (EKSource* source in eventStore.sources) {
if (source.sourceType == EKSourceTypeLocal)
{
localSource = source;
break;
}
if (!localSource)
return;
calendar = [EKCalendar calendarWithEventStore:eventStore];
calendar.source = localSource;
calendar.title = calendarName;
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
calendar = [eventStore calendarWithIdentifier:self.calendarIdentifier];
event.calendar = calendar;
// Set the start date to the current date/time and the event duration to one hour
NSDate *startDate = [NSDate date];
event.startDate = startDate;
event.endDate = [startDate dateByAddingTimeInterval:3600];
//And to save the event to the event database:
NSError *error = nil;
BOOL result = [eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&error];
if (result)
{
NSLog(#"Saved event to event store.")
}
else
{
NSLog(#"Error saving event: %#.", saveError);
}
NSError* error;
bool success= [eventStore saveCalendar:calendar commit:YES error:&error];
if (error != nil)
{
NSLog(error.description);
}
}

How can I programmatically create an iCal event in the default calendar?

How can I use Objective-C to programmatically create an iCal event in the default calendar? I want to check whether the event already exists and set the button state accordingly.
An example of how to programmatically create an iCAL event in the default calendar, using Objective-C. The code checks if the event already exists, and sets the button state accordingly. Here is the code by #codeburger:
-(void)initCalendar {
// An array of 1 dictionary object, containing START and END values.
NSMutableArray* pvDict = [[NSMutableArray alloc] initWithContentsOfURL:[NSURL URLWithString:PV_URL ]];
// Check if the private view event already exists in the default calendar.
// Then set the calendar button state.
// Get a entry point to the Calendar database.
self.store = [[EKEventStore alloc ] init ];
// Get an array of all the calendars.
NSArray *calendars = store.calendars;
// Get the default calendar, set by the user in preferences.
EKCalendar *defaultCal = store.defaultCalendarForNewEvents;
// Find out if this calendar is modifiable.
BOOL isDefaultCalModifiable = defaultCal.allowsContentModifications ;
// Create an event in the default calendar.
self.event = [ EKEvent eventWithEventStore:store ];
self.event.title = CHELSEA_SPACE ;
self.event.location = CHELSEA_ADDRESS ;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyy-MM-dd HH:mm:ss.S"];
NSString *startString = [[ pvDict objectAtIndex:0] objectForKey:#"starts" ];
NSDate *dateStart = [dateFormatter dateFromString:startString];
NSString *endString = [[ pvDict objectAtIndex:0] objectForKey:#"ends" ];
NSDate *dateEnd = [dateFormatter dateFromString:endString];
self.event.startDate = dateStart;
self.event.endDate = dateEnd;
self.event.calendar = defaultCal ;
// Alternative code to add 2.5 hours to start time.
// [[NSDate alloc] initWithTimeInterval:9000 sinceDate:event.startDate];
// Search for events which match this date/time start and end.
// Compare the matched events by event TITLE.
NSPredicate *predicate = [store predicateForEventsWithStartDate:event.startDate
endDate:event.endDate calendars:calendars];
NSArray *matchingEvents = [store eventsMatchingPredicate:predicate];
self.calendarButton.enabled = NO;
if( ! isDefaultCalModifiable ) {
// The default calendar is not modifiable
return ;
}
if ( [ matchingEvents count ] > 0 ) {
// There are already event(s) which match this date/time start and end.
// Check if this event is the PV
EKEvent *anEvent;
int j;
for ( j=0; j < [ matchingEvents count]; j++) {
anEvent = [ matchingEvents objectAtIndex:j ] ;
if([ CHELSEA_SPACE isEqualToString: anEvent.title ]) {
// PV event already exists in calendar.
return;
}
}
[ anEvent release ];
}
self.calendarButton.enabled = YES;
[ pvDict release ];
}
-(void)addEventToCalendar:(id)sender {
NSError *error;
BOOL saved = [self.store saveEvent:self.event span:EKSpanThisEvent error:&error];
NSLog(#"Saved calendar event = %#\n", (saved ? #"YES" : #"NO"));
self.calendarButton.enabled = NO;
}
I've seen this question with no answer and felt like it should be edited giving full credit to #codeburger.
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
NSDate *date = [[NSDate alloc ]init];//today,s date
event.title = #"remainder";//title for your remainder
event.startDate=date;//start time of your remainder
event.endDate = [[NSDate alloc] initWithTimeInterval:1800 sinceDate:event.startDate];//end time of your remainder
NSTimeInterval interval = (60 *60)* -3 ;
EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:interval]; //Create object of alarm
[event addAlarm:alarm]; //Add alarm to your event
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
NSString *ical_event_id;
//save your event
if([eventStore saveEvent:event span:EKSpanThisEvent error:&err]){
ical_event_id = event.eventIdentifier;
NSLog(#"%#",ical_event_id);
}
for more info check this link
sample for EKEvent