Removing events from iPhone calendar with EKEventStore - iphone

I'm trying to remove events that i have created from the iPhone calendar.
I tried this, but it always returns NO:
[eventStore removeEvent:event span:EKSpanThisEvent error:&err];
I created the event as follows and it works:
eventStore = [[EKEventStore alloc] init];
event = [EKEvent eventWithEventStore:eventStore];
event.title = #"EVENT TITLE";
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd:HH:mm"];
NSDate * date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:#"2010-8-15:12:30"];
[date retain];
event.startDate = date;
event.endDate = [[NSDate alloc] initWithTimeInterval:600 sinceDate:event.startDate];
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
Is there a way to remove this event? Or it would be be better that if I try to write this event again it only modifies it instead of creating a new one.
Thanks,

After creating the event I save the eventIdentifier in an array:
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
NSString* str = [[NSString alloc] initWithFormat:#"%#", event.eventIdentifier];
[arrayofCalIDs addObject:str];
To delete the events:
EKEventStore* store = [[[EKEventStore alloc] init] autorelease];
EKEvent* event2 = [store eventWithIdentifier:[arrayofCalIDs objectAtIndex:i]];
if (event2 != nil) {
NSError* error = nil;
[store removeEvent:event2 span:EKSpanThisEvent error:&error];
}
[myPath release];

Just an FYI for the answer above. It is found on the web on with this link:
http://tech.vniup.com/index.php/iphone/objective-c/how-to-delete-event-from-iphone-calendar-programmatically.html
My only suggestion is that if you are building an array of objects each object ideally would be the event. Then do a reverse array operation because the latest event will always be at the bottom.
NSMutableArray *reverseArray = [NSMutableArray arrayWithCapacity:[eventsList count]];
for (id element in [eventsList reverseObjectEnumerator]) {
[reverseArray addObject:element];
}
eventsList = reverseArray;
And also in the display of the events be nice to your users and display the start date of the event.
Anyway, after you have an array objects that are EKEvents you can do this which is MUCH easier.
EKEvent *eventToRemove = [myEventStore eventWithIdentifier:thisEvent.eventIdentifier ];
if ([eventToRemove.eventIdentifier length] > 0) {
NSError* error = nil;
[myEventStore removeEvent:eventToRemove span:EKSpanThisEvent error:&error];
}
Then you can remove that same event from you array of events for the table display....easy!

Related

How to delete event from iCal added from my app.?

I'm developing an app in which when user add any event as his favorite, I'm adding that event to iCal but how do i remove that event from iCal if user removes that particular event from his favorite.?
Here is my code:
NSDate *date = [NSDate dateWithTimeIntervalSince1970:[[self.parentDetailArray valueForKey:#"start_time_num"] intValue]];
NSDateFormatter *dateformatter=[[NSDateFormatter alloc]init];
[dateformatter setLocale:[NSLocale currentLocale]];
[dateformatter setDateFormat:#"dd-MM-yyyy"];
NSString *dateString=[dateformatter stringFromDate:date];
EKEventStore *eventStore = [[EKEventStore alloc] init];
if([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)])
{
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted){
//---- codes here when user allow your app to access theirs' calendar.
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = title;
event.startDate = date;
event.endDate = [[NSDate alloc] initWithTimeInterval:1000 sinceDate:event.startDate];
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
// Here I'm trying to get the identifier of that event but m getting only (null)
self.str = [[NSString alloc] initWithFormat:#"%#", event.eventIdentifier];
[self.arrayofEventId addObject:self.str];
//[self performCalendarActivity:eventStore];
}else
{
//----- codes here when user NOT allow your app to access the calendar.
}
}];
}
else {
//---- codes here for IOS < 6.0.
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = #"Testing for calendar";
event.startDate = [[NSDate alloc] init];
NSLog(#"%#",event.startDate);
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
//[self performCalendarActivity:eventStore];
}
How do i get the event identifier n remove that particular event from iCal. any help would be appreciated.
You could write all app generated event ID's to file and then load them back up next time the app loads. This way you can keep track of which events your app created. Then you may want to try this method:
- (BOOL)removeEvent:(EKEvent *)event span:(EKSpan)span commit:(BOOL)commit error:(NSError **)error
Save with this:
NSString *id = [[NSString alloc] initWithFormat:#"%#", event.eventIdentifier];
Remove with this:
EKEvent *event = [eventStore eventWithIdentifier:id];
NSError *error = nil;
[eventStore removeEvent:event span:EKSpanThisEvent error:&error];
Apple has documentation on the EKEventStore here.

Add event to Birthday calendar in iOS

I wrote this code but it doesn't work, can you help me please? I'm stuck on it for last 2 hours.
- (IBAction)addBirthday:(id)sender {
NSString *name = self.textField.text;
NSDate *date = [self.datePicker date];
EKEventStore *eventStore = [[EKEventStore alloc] init];
[eventStore calendarsForEntityType:EKEntityTypeEvent];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = [NSString stringWithFormat:#"%#’s Birthday", name];
event.startDate = date;
event.endDate = date;
NSArray *calendars = [eventStore
calendarsForEntityType:EKEntityTypeEvent];
NSLog(#"ARRAY: %#", [calendars objectAtIndex:0]);
[event setCalendar: [calendars objectAtIndex:0]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
}
The birthdays calendar is likely read only

How to update and remove calendar event?

I am doing a sample application using iPhone calendar events. I am able to save the calendar event from my application to iPhone native calendar. While saving I am saving the saved event identifier in to my application database. Now I need to update the same event or remove the event. How can I do using the event Identifier which is saved in my database. Here is the piece of code for saving the event and saving the event identifier into database.
ENTITYCMAPPIPHONE *appointmentCM;
NSError *error;
NSFetchRequest *fetchRequest =
[managedObjectModel fetchRequestFromTemplateWithName:#"FetchForIphoneAppointment" substitutionVariables:nil];
NSArray *fetchedObjects= [context executeFetchRequest:fetchRequest error:nil];
int fetchCount = [fetchedObjects count];
if ([fetchedObjects count]>0) {
for (appointmentCM in fetchedObjects) {
NSLog(#"Appoint subject %#", appointmentCM.subject);
NSLog(#"APP notes %#", appointmentCM.notes);
appoint_ID = [appointmentCM.mobAppID intValue];
NSDateFormatter *f = [[NSDateFormatter alloc] init];
[f setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
NSDate *date = [f dateFromString:#"2012-09-10 13:55:15"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSInteger units = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekdayCalendarUnit;
NSDateComponents *components = [calendar components:units fromDate:date];
NSInteger year = [components year];
NSInteger day = [components day];
NSDateFormatter *weekDay = [[[NSDateFormatter alloc] init] autorelease];
[weekDay setDateFormat:#"EEE"];
NSDateFormatter *calMonth = [[[NSDateFormatter alloc] init] autorelease];
[calMonth setDateFormat:#"MMMM"];
EKEventStore *eventStore1 = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore1];
event.title = appointmentCM.subject;
event.notes = appointmentCM.notes;
event.startDate = date;
event.endDate = [[NSDate alloc] initWithTimeInterval:600 sinceDate:event.startDate];
[event setCalendar:[eventStore1 defaultCalendarForNewEvents]];
NSError *err;
[eventStore1 saveEvent:event span:EKSpanThisEvent error:&err];
eventID = [[NSString alloc] initWithFormat:#"%#", event.eventIdentifier];
[self updateIphoneCalendarEventID];
}
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
}
-(void)updateIphoneCalendarEventID{
NSError *error;
NSDictionary *subs;
subs = [NSDictionary
dictionaryWithObjectsAndKeys:[NSNumber numberWithInt:appoint_ID], #"search_appID", nil];
NSFetchRequest *fetchRequestCheckNil =
[managedObjectModel fetchRequestFromTemplateWithName:
#"FetchEditIphoneCalendar" substitutionVariables:subs];
NSArray *fetchedObjects=[context executeFetchRequest:fetchRequestCheckNil error:nil];
if ([fetchedObjects count]>0) {
for (ENTITYAPPOINTMENTS *appDetails
in fetchedObjects) {
[self updateDBModelForAppointments:appDetails];
}
}
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}
-(void)updateDBModelForAppointments:(ENTITYAPPOINTMENTS *)contactDetails{
contactDetails.iphoneAppID = eventID;
}
EKEventStore *eventStore = [[[EKEventStore alloc] init] autorelease];
NSString *idenfier = nil;//.....;// Get identifier stored in your application database
NSError *err = nil;
EKEvent *ev = [eventStore eventWithIdentifier:idenfier];
if(err){
NSLog(#"Error: %#",[err localizedDescription]);
}
else
{
// manipulate event...
ev.title = #"new title";
ev.location = #"new location";
// or remove:
[eventStore removeEvent:ev span:EKSpanFutureEvents commit:NO error:&err];
}

Why can't I code an EKEvent title?

I am using the following code to create an event within the iPhone's calendar;
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = #"DHSB Assignment: %#", Assignment1.text;
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];
[EKEventStore release];
NSLog(#"Successfully added '%#' to the calendar", Assignment1.text);
Why is this saving an event with the name "DHSB Assignment: %#" rather than "DHSB Assignment: Example Text"?
Thank you.
event.title = [NSString stringWithFormat:#"DHSB Assignment: %#", Assignment1.text];
Your current code is equivalent to
[event setTitle:#"DHSB Assignment: %#"];
[Assignment1 text];
…which is valid, so it compiles and runs fine even though it isn’t doing what you want.

Manage iPhone Calendar event from our application

The following is my code
NSLog(#"%#", thisEvent1.title);
EKEvent *thisEvent = [EKEvent eventWithEventStore:eventStore];
eventStore = [[EKEventStore alloc] init];
thisEvent = [EKEvent eventWithEventStore:eventStore];
NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd:HH:mm"];
NSDate * date = [[NSDate alloc] init];
date = [dateFormatter dateFromString:[itsStartDate objectAtIndex:indexPath.row]];
[date retain];
thisEvent.startDate = [dateFormatter dateFromString:[itsStartDate objectAtIndex:indexPath.row]];
thisEvent.endDate = [dateFormatter dateFromString:[itsEndDate objectAtIndex:indexPath.row]];
thisEvent.notes = [itsNotes objectAtIndex:indexPath.row];
thisEvent.title = [itsTitle objectAtIndex:indexPath.row];
thisEvent.location = [itsLocation objectAtIndex:indexPath.row];
// thisEvent.allDay = TRUE;
NSMutableArray *myAlarmsArray = [[NSMutableArray alloc] init];
EKAlarm *alarm1 = [EKAlarm alarmWithRelativeOffset:-[[itsAlertOne objectAtIndex:indexPath.row] intValue]]; // 1 Hour
// EKAlarm *alarm2 = [EKAlarm alarmWithRelativeOffset:-86400]; // 1 Day
[myAlarmsArray addObject:alarm1];
//[myAlarmsArray addObject:alarm2];
thisEvent.alarms = myAlarmsArray;
[myAlarmsArray release];
//setting the Reuccurence rule
NSString * test1 = [itsRecurrenceFrequency objectAtIndex:indexPath.row];
BOOL isRecurrenceFrequencyExists = TRUE;
EKRecurrenceFrequency recurrenceFrequency;
if ([test1 isEqualToString: #"EKRecurrenceFrequencyDaily"]) {
recurrenceFrequency = EKRecurrenceFrequencyDaily;
}else if([test1 isEqualToString: #"EKRecurrenceFrequencyWeekly"]){
recurrenceFrequency = EKRecurrenceFrequencyWeekly;
}else if([test1 isEqualToString: #"EKRecurrenceFrequencyMonthly"]){
recurrenceFrequency = EKRecurrenceFrequencyMonthly;
}else if([test1 isEqualToString: #"EKRecurrenceFrequencyYearly"]){
recurrenceFrequency = EKRecurrenceFrequencyYearly;
}else{
isRecurrenceFrequencyExists = FALSE;
}
if(isRecurrenceFrequencyExists){
EKRecurrenceRule * recurrenceRule = [[EKRecurrenceRule alloc]
initRecurrenceWithFrequency:recurrenceFrequency
interval:[[itsRecurrenceInterval objectAtIndex:indexPath.row]intValue]
end:nil];
if (thisEvent.endDate != nil) {
EKRecurrenceEnd * end = [EKRecurrenceEnd recurrenceEndWithEndDate:thisEvent.endDate];
recurrenceRule.recurrenceEnd = end;
}else {
thisEvent.endDate = thisEvent.startDate;
}
thisEvent.recurrenceRule = recurrenceRule;
[recurrenceRule release];
}
[thisEvent setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:thisEvent span:EKSpanFutureEvents error:&err];
NSLog(#"%#", thisEvent.eventIdentifier);
[self.eventsList addObject:thisEvent];
In this code I have the Event id of my calendar event.
Now I want to update the event with the changes however Its not updating the previously created event.
Second I Need to know is it possible to capture the changes in calendar event they made in iPhone Calendar including deleting an event.
Can we delete the calendar event using the eventid?
Please help me if any one know the answer.. Thank you in advance.
Regards,
Dilip Rajkumar
Event can be created by this:
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
NSString* str = [[NSString alloc] initWithFormat:#"%#", event.eventIdentifier];
[arrayofCalIDs addObject:str];
You can delete the event using this:
EKEventStore* store = [[[EKEventStore alloc] init] autorelease];
EKEvent* event2 = [store eventWithIdentifier:[arrayofCalIDs objectAtIndex:i]];
if (event2 != nil) {
NSError* error = nil;
[store removeEvent:event2 span:EKSpanThisEvent error:&error];
}
[myPath release];
For Updating Event you cannot directly access any method as it is not available in iOS. So, you can do one thing for this.
(1) First remove the event with eventID.
(2) Create new Event using the same information of the last deleted event.