Setting Calendar Event From Date Picker - ios

I am setting a calendar event from code in my app, and setting the date from my date picker. Here is what I have:
-(void)setCalenderEvent
{
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
NSDate *startDate = [[NSDate alloc] init];
NSDate *endDate = [[NSDate alloc] init];
event.title = #"Test from date picker";
// event.startDate = startDate;
// event.endDate = endDate;
NSDate *selectedDate = self.datePickerForReminder.date;
event.startDate = selectedDate;
event.allDay = NO;
event.notes = #"Created by Quick Reminders!!";
/* iOS 6 requires the user grant your application access to the Event Stores */
if ([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)])
{
/* iOS Settings > Privacy > Calendars > MY APP > ENABLE | DISABLE */
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
if ( granted )
{
NSLog(#"User has granted permission!");
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
if (err == noErr){
NSLog(#"No Error");
}
[startDate release];
[endDate release];
[eventStore release];
}
else
{
NSLog(#"User has not granted permission!");
}
}];
}
}
Can anyone tell me what I am doing wrong?
Thanks!

I was able to get it! You need a span time (add end time).
event.endDate = [selectedDate dateByAddingTimeInterval:30*60];

Related

delete all events from calendar

i am creating an iOS application, which get dates from the server and add them events to the calendar:
I'm adding them with this code :
- (void)addReminderWithTitle:(NSString *)title date:(NSString *)date {
NSString *dateString = date;
NSDateFormatter *dateFormatter = [NSDateFormatter new];
[dateFormatter setDateFormat:#"yyyy-MM-dd hh:mm:ss"];
NSDate *dateFromString = [dateFormatter dateFromString:dateString];
[dateFromString dateByAddingTimeInterval:-60*30];
EKEventStore *eventStore = [[EKEventStore alloc] init];
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted) {
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = title;
event.startDate = dateFromString;
//[NSDate date]; //today
event.endDate = [event.startDate dateByAddingTimeInterval:60*60]; //set 1 hour meeting
event.calendar = [eventStore defaultCalendarForNewEvents];
NSError *err = nil;
[eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
}}];
}
and I need a function, that will delete all the events on a specific action from the user.
any help?
You need to get an array of all events from calendar and filter them in an array by some identifier, date or title so that you can get your own added events.
// Create the predicate from the event store's instance method
NSPredicate *predicate = [store predicateForEventsWithStartDate:oneDayAgo endDate:oneYearFromNow calendars:nil];
// Fetch all events that match the predicate
NSArray *events = [store eventsMatchingPredicate:predicate];
Then loop over the array of events and delete them like this
EKEventStore* store = [[EKEventStore alloc] init];
EKEvent* event2 = [store eventWithIdentifier:[arrayofCalIDs objectAtIndex:i]];
if (event2 != nil) {
NSError* error = nil;
[store removeEvent:event2 span:EKSpanThisEvent error:&error];
}

EKEventStore saveEvent adding events a hour later

I believe this worked before but now when I add a event to my calendar when I am in time zone set to automatically or Louisville which is EDT, and I add an event that is EDT it adds it to my calendar a hour ahead.
I do this on another app that has events in CST, and when I add them to my calendar, it adds them just fine. Is my code wrong or something?
- (void)viewWillAppear:(BOOL)animated {
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone timeZoneWithName:self.event.timeZone]];
[dateFormat setDateFormat:#"yyyy-MM-ddHH:mm:ss"];
self.startDate = [dateFormat dateFromString:self.game.dateTime];
self.endDate = [[NSDate alloc] initWithTimeInterval:60*self.event.gameDuration sinceDate:self.startDate];
}
- (void) addToCalendar
{
EKEventStore *eventStore = [[EKEventStore alloc] init];
if ([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)]){
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
for (EKSource *source in eventStore.sources)
{
if (source.sourceType == EKSourceTypeCalDAV || source.sourceType == EKSourceTypeLocal)
{
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = [NSString stringWithFormat:#"%# vs. %#", self.game.awayTeam.team.name, self.game.homeTeam.team.name];
event.location = [NSString stringWithFormat:#"%# - %#", self.game.venue.name, self.game.venue.court];
event.startDate = self.startDate;
event.endDate = self.endDate;
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
[eventStore saveEvent:event span:EKSpanThisEvent error:&err];
if(err) {
dispatch_async(dispatch_get_main_queue(), ^{
[self showAlert:#"Error" desc:#"There was a problem adding this game to your calendar"];
});
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
[self showAlert:#"Success" desc:#"Game added to your calendar"];
});
}
break;
}
}
}];
}
}
I found out Apple uses their own timezone strings so I just did a translation from Windows Timezones to Apple when sending it via our API.

Choosing Calendar to add an iOS event

I'm trying to add events to the calendar in iOS devices, for now I've got to add an event to the defaultCalendarForNewEvents calendar, but what I want is to be able to choose a calendar that has already been created in which I want to add the event.
For example in the following capture it is seen that there is an iphone calendar and then there may be 1 or several gmail created
What I want to do is that you can choose the calendar in which you want to add the event, this calendar must be created earlier, not that the system chooses the calendar.
Any recommendations? Any examples?
P.D: I'm starting to code with objective-c and ios
Code to add events I'm testing and it works:
- (void) addEventCalendar: (Evento_DTO *) evento {
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
EKReminder *reminder = [EKReminder reminderWithEventStore:eventStore];
event.title = #"Test Event";
reminder.title = #"Test reminder";
NSDate *cDate = [NSDate date];
NSLog(#"current date %#", cDate);
/*NSDateComponents *startDateComponents = [[[NSDateComponents alloc] init] autorelease];
[startDateComponents setDay:12];
[startDateComponents setMonth:12];
[startDateComponents setYear:2012];
[startDateComponents setHour:12];
[startDateComponents setMinute:18];
NSDateComponents *endDateComponents = [[[NSDateComponents alloc] init] autorelease];
[endDateComponents setDay:12];
[endDateComponents setMonth:12];
[endDateComponents setYear:2012];
[endDateComponents setHour:12];
[endDateComponents setMinute:18];
[endDateComponents setSecond:20];*/
//event.startDate = cDate;
//event.endDate = [cDate dateByAddingTimeInterval:15.0];
event.startDate = [cDate dateByAddingTimeInterval:((5*60*60) + (30 * 60) + 15)];
event.endDate = [cDate dateByAddingTimeInterval:((5*60*60) + (30 * 60) + 30)];
//event.startDate = [[NSCalendar currentCalendar] dateFromComponents:startDateComponents];
//event.endDate = [[NSCalendar currentCalendar] dateFromComponents:endDateComponents];
reminder.completionDate = [cDate dateByAddingTimeInterval:((5*60*60) + (30 * 60) + 10)];
NSLog(#"startdate %#", event.startDate);
NSLog(#"enddate %#", event.endDate);
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
//[reminder setCalendar:[eventStore defaultCalendarForNewReminders]];
NSError *error = nil;
[eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&error];
//[eventStore saveReminder:reminder commit:YES error:&error];
}
First of all, thank #NarendraPandey and #nehamishra for the help provided
I have given the solution to my problem, which will then put the solution in case someone can serve you.
I have created a method to obtain the available calendars that are local and those of gmail, the code is the following one:
- (NSMutableArray*) getCalendars {
NSMutableArray *res =[[NSMutableArray alloc] init];
EKEventStore *eventStore = [[EKEventStore alloc] init];
EKEntityType type = EKEntityTypeEvent;
NSArray *calendars = [eventStore calendarsForEntityType: type];
for ( EKCalendar *cal in calendars )
{
if (cal.type == EKCalendarTypeCalDAV || cal.type == EKCalendarTypeLocal ){
NSLog(#"cal nombre:- %# ", cal.title);
[res addObject: cal];
}
}
return res;
}
Then to show the list of calendars so that the user can select one and enter the events there, I found that Ihave to use an Action Sheet, although I have seen that it was deprecated according to some forum comments Of StackOverflow, so I used UIAlertController, being as follows:
NSMutableArray* cals = [self getCalendars];
if([cals count] > 0){//Comprobamos que existan calendarios
UIAlertController *alert = [UIAlertController alertControllerWithTitle:AMLocalizedString(#"calendar_dialog_info", #"")
message:nil
preferredStyle:UIAlertControllerStyleActionSheet];
for ( EKCalendar *cal in cals )
{
UIAlertAction *calAction = [UIAlertAction actionWithTitle: cal.title
style:UIAlertActionStyleDefault handler:^(UIAlertAction * action) {
NSLog(#"You pressed button %# ", cal.title);
[self descargarCalendario: cal];
}];
[alert addAction:calAction];
}
UIAlertAction* cancel = [UIAlertAction
actionWithTitle:AMLocalizedString(#"cancelar", #"")
style:UIAlertActionStyleCancel
handler:^(UIAlertAction * action)
{
[alert dismissViewControllerAnimated:YES completion:nil];
}];
[alert addAction:cancel];
[self presentViewController:alert animated:YES completion:nil];
}else{
NSLog(#"No hay calendarios");
}
Where the [self downloadCalendario: cal]; function is responsible for downloading some events from a web service and adding them to the chosen calendar.
Resulting in the following view to choose the calendar:
And the code to add the event to the selected calendar is:
-(void)addEventOnCalendar: (EKCalendar *) cal{
EKEventStore *store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) {
return;
}
EKEvent *event = [EKEvent eventWithEventStore:store];
event.title = #"Test";
NSDate *cDate = [NSDate date];
event.startDate = [cDate dateByAddingTimeInterval:((5*60*60) + (30 * 60) + 15)];
event.endDate = [cDate dateByAddingTimeInterval:((5*60*60) + (30 * 60) + 15)];
//event.calendar = [store defaultCalendarForNewEvents];
event.calendar = [store calendarWithIdentifier: cal.calendarIdentifier];
NSError *err = nil;
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
}];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Message" message:#"Event Successfully added " delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
}
I hope it helps somebody.
Try this by creating new calendar.
-(EKEvent*)createEvent:(EKEventStore*)eventStore{
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = #"New Event";
event.startDate = [NSDate date];
event.endDate =[NSDate date];
event.location=#"Location";
event.allDay = YES;
event.notes =#"Event description";
NSString* calendarName = #"Calendar";
EKCalendar* calendar;
EKSource* localSource;
for (EKSource *source in eventStore.sources){
if (source.sourceType == EKSourceTypeCalDAV &&
[source.title isEqualToString:#"iCloud"]){
localSource = source;
break;
}
}
if (localSource == nil){
for (EKSource *source in eventStore.sources){
if (source.sourceType == EKSourceTypeLocal){
localSource = source;
break;
}
}
}
calendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:eventStore];
calendar.source = localSource;
calendar.title = calendarName;
NSError* error;
[eventStore saveCalendar:calendar commit:YES error:&error];
return event;
}
Hope it will work.
Let me know if you have any query.
-(void)addEventOnCalendar{
EKEventStore *store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) {
return;
}
EKEvent *event = [EKEvent eventWithEventStore:store];
event.title = #"What ever You want to save as your event";
event.startDate = selectedDate;
event.endDate = selectedDate1;
event.calendar = [store defaultCalendarForNewEvents];
NSError *err = nil;
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
}];
UIAlertView *alert=[[UIAlertView alloc]initWithTitle:#"Message" message:#"Event Successfully added in Calender" delegate:self cancelButtonTitle:#"ok" otherButtonTitles:nil, nil];
[alert show];
}

Ekevents gets adding multiple times in calendar?

In my application i am adding an event to devices calendar.I am doing like this
if ([db.saveCalenderSettings isEqualToNumber:[NSNumber numberWithBool:YES]]){
NSPredicate *predicateForEventOnDate = [store predicateForEventsWithStartDate:strtdate endDate:[strtdate dateByAddingTimeInterval:60*60] calendars:nil];
NSArray *eventsOnDate = [store eventsMatchingPredicate:predicateForEventOnDate];
__block BOOL eventExists = NO;
[eventsOnDate enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
EKEvent *eventToCheck = (EKEvent*)obj;
if([note isEqualToString:eventToCheck.notes]) {
eventExists = YES;
*stop = YES;
}
}];
NSLog(#"%#",eventsOnDate);
if(! eventExists) {
NSLog(#"Event not exists so adding");
EKEvent *event = [EKEvent eventWithEventStore:store];
event.title = subject; //give event title you want
event.notes = note ;
event.startDate = strtdate;
event.endDate = [event.startDate dateByAddingTimeInterval:60*60];
event.calendar = [store defaultCalendarForNewEvents];
// EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:60*15*-1];
// event.alarms = [NSArray arrayWithObject:alarm];
NSError *err = nil;
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
if (!err) {
[db setSavedtocalender:#"yes"];
}
else {
// NSLog(#" Event not created");
[db setSavedtocalender:#"no"];
}
}
else {
NSLog(#"Event exists");
[db setSavedtocalender:#"yes"];
}
}
But the problem is the same event gets added multiple times in the default calendar .Can anybody tells me where i am going wrong?
Hi For each and every event one id is alloted.
Please Check is the event is added or not.If event added then store event id and check agin before saving event again.
For getting Event Id :
//save the event id if you want to access this later
NSString *eventId=event.eventIdentifier;
For Future Refernce :
// To add event in Calender App
EKEventStore *store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) { return; }
EKEvent *event = [EKEvent eventWithEventStore:store];
event.title = #"To meet Chandu.";
event.startDate = [NSDate date]; //today
event.endDate = [event.startDate dateByAddingTimeInterval:60*60]; //set 1 hour meeting
event.calendar = [store defaultCalendarForNewEvents];
event.location=#"Sandriver Technologies";
NSError *err = nil;
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
NSLog(#"%#",event.eventIdentifier); //save the event id if you want to access this later
eventId=event.eventIdentifier;
}];
//to remove event from app
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) { return; }
EKEvent* eventToRemove = [store eventWithIdentifier:eventId];
if (eventToRemove) {
NSError* error = nil;
[store removeEvent:eventToRemove span:EKSpanThisEvent commit:YES error:&error];
}
}];
// Note: Get all event list
//To get Appropriate calender
NSCalendar *calendar = [NSCalendar currentCalendar];
if ([store respondsToSelector:#selector(requestAccessToEntityType:completion:)])
{
/* iOS Settings > Privacy > Calendars > MY APP > ENABLE | DISABLE */
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
if ( granted )
{
NSLog(#"User has granted permission!");
// Create the start date components
NSDateComponents *oneDayAgoComponents = [[NSDateComponents alloc] init];
oneDayAgoComponents.day = -1;
NSDate *oneDayAgo = [calendar dateByAddingComponents:oneDayAgoComponents
toDate:[NSDate date]
options:0];
// Create the end date components
NSDateComponents *oneYearFromNowComponents = [[NSDateComponents alloc] init];
oneYearFromNowComponents.year = 1;
NSDate *oneYearFromNow = [calendar dateByAddingComponents:oneYearFromNowComponents
toDate:[NSDate date]
options:0];
// Create the predicate from the event store's instance method
NSPredicate *predicate = [store predicateForEventsWithStartDate:oneDayAgo
endDate:oneYearFromNow
calendars:nil];
// Fetch all events that match the predicate
NSArray *events = [store eventsMatchingPredicate:predicate];
NSLog(#"The content of array is%#",events);
}
else
{
NSLog(#"User has not granted permission!");
}
}];
}

How to create a reminder and store reminder on iPhone Calender

I am new to programming I have made a Reminder App which saves the events on iCal and now i want to delete that events through the coding in the project, my code for creating events in iCal is below-
-(void) setReminderInPhone {
NSString *dateWithTime = [NSString stringWithFormat:#"%# %#",calenderDtl.dateInString,calenderDtl.openTimeUTC];
NSString *mrktName = mrktDtl.marketName;
//dateWithTime = #"2016-04-02 04:10 am";
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
fmt.dateFormat = #"yyyy-MM-dd hh:mm a";
[fmt setAMSymbol:#"am"];
[fmt setPMSymbol:#"pm"];
fmt.timeZone = [NSTimeZone timeZoneWithName:#"UTC"];
NSDate *utc = [fmt dateFromString:dateWithTime];
fmt.dateFormat = #"yyyy-MM-dd hh:mm a";
fmt.timeZone = [NSTimeZone systemTimeZone];
NSString *local = [fmt stringFromDate:utc];
NSDate *localDate = [fmt dateFromString:local];
EKEventStore *store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) { return; }
EKEvent *event = [EKEvent eventWithEventStore:store];
event.title = mrktName;
event.startDate = localDate; //test
event.endDate = [event.startDate dateByAddingTimeInterval:60*2];
event.calendar = [store defaultCalendarForNewEvents];
NSError *err = nil;
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
}];
}
Try following to remove event from Calendar.
EKEvent *eventToRemove = [eventStore eventWithIdentifier:eventIdentifier];
if (eventToRemove)
{
NSError* error = nil;
[eventStore removeEvent:eventToRemove span:EKSpanThisEvent commit:YES error:&error];
}
You will get the Value of eventIdentifier at the time of creating event in iCalendar as following :
//Adding Events to default iOS calendar for Making Reminders
-(NSString *)addEventToCalendar: (NSString *)title withDate:(NSString *)date{
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = [NSString stringWithFormat:#"Pregnancy Workout Advisor - Event: %#",title];
event.startDate = [dateFormatter dateFromString:date];
event.endDate = [event.startDate dateByAddingTimeInterval:60*60]; //set 1 hour meeting
event.allDay = YES;
[dateFormatter setDateFormat:#"YYYY-MM-dd"];
EKAlarm *alarm = [EKAlarm alarmWithAbsoluteDate:[NSDate dateWithTimeInterval:9*60*60 sinceDate:[dateFormatter dateFromString:date]]];
[event addAlarm:alarm];
event.calendar = [eventStore defaultCalendarForNewEvents];
NSError *err = nil;
[eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
return event.eventIdentifier; }
In this above method, you will get a eventIdentifier for each event which you're adding to calendar. Store the eventIdentifier to CoreData/Sqlite, whatever..
So that, when you need to delete that event, just give that eventIdentifier. This will surely delete from Calendar.
Hope it helps...
try this code, its working for me,
EKEventStore *store = [[EKEventStore alloc] init];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) return;
EKEvent* eventToRemove = [store eventWithIdentifier:[eventIdendifier objectAtIndex:indexPath.row]];
if (eventToRemove) {
[eventToRemove setCalendar:[store defaultCalendarForNewEvents]];
NSError* err = nil;
[store removeEvent:eventToRemove span:EKSpanThisEvent commit:YES error:&err];
dispatch_async(dispatch_get_main_queue(), ^{
[eventIdendifier removeObjectAtIndex:indexPath.row];
});
}
}];
i have give eventIdentifier value, its NSMutableArray value. first you add the event in Event Store you had each event got each event identifier value, its automatically save to eventIdentifier and get the identifier value method is below,
EKEventStore *store = [EKEventStore new];
if ([store respondsToSelector:#selector(requestAccessToEntityType:completion:)])
{
/* iOS Settings > Privacy > Calendars > MY APP > ENABLE | DISABLE */
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
if ( granted )
{
NSPredicate *predicate = [store predicateForEventsWithStartDate:date1 endDate:[date1 dateByAddingTimeInterval:23.96 * 60.0 * 60.0] calendars:nil];
NSMutableArray *eventsVal = (NSMutableArray *)[store eventsMatchingPredicate:predicate];
for (int i = 0; i<eventsVal.count; i++) {
[eventIdendifier addObject:[[eventsVal objectAtIndex:i] eventIdentifier]];
}
}
}];
}
its predicate the start date to end date check then got all events particular date and also add object from eventIdentifier value if the value help to show event Values, remove events etc
hope its helpful

Resources