Loading bulk event in ios calendar get error - ios

I am trying to do a massive load of events on a ios calendar either local or in gmail (the calendar chooses the user as I describe in the following answer) using objective-c.
Adding an event with the functions I've put below works fine for me, but when I have to do a massive load of eg 527 events (since I'm trying to add a student's school calendar) it does not work correctly.
When doing the bulk load I inserted well about 100 events or so and then it starts to crash and crash the app.
The errors that it gives me are the following:
2016-11-17 17:23:35.966 [230:11481] Calendar was not set: 1 Error
Domain=EKErrorDomain Code=1 "No calendar selected."
UserInfo={NSLocalizedDescription=No calendar selected.}
2016-11-17 17:23:49.545 [230:12644] Connectioninterrupted!
2016-11-17 17:23:49.568[230:12587] Error getting changed object IDs
since timestamp 501092601.149441 from daemon: Error
Domain=NSMachErrorDomain Code=4097 "unknown error code"
My question is this: Is there any error in my massive loading approach or in the functions I have done? or else Is there any other better way to do a massive load of events?
Function that inserts the list of events:
- (int) addCalendarEvents: (EKCalendar *) cal {
int num = 0;
for (int i=0; i < [calendario.eventos count]; i++) {
NSDictionary * nextDict = [calendario.eventos objectAtIndex:i];
Evento_DTO * evento_dto = [[Evento_DTO alloc] initWithEventos:nextDict];
BOOL res = [self addEventCalendar: evento_dto calendar: cal];
if(res){
num++;
}
}
return num;
}
And the function that adds the event to the calendar is as follows:
-(BOOL)addEventCalendar: (Evento_DTO *) evento calendar: (EKCalendar *) cal{
__block BOOL res = NO;
if (!SYSTEM_VERSION_LESS_THAN(#"6.0")) {
// iOS 6 and later
EKEventStore *eventStore = [[EKEventStore alloc] init];
//We get the dates of the event
Fecha_DTO *fechaStart = [[Fecha_DTO alloc] initWithFecha:(NSDictionary *)evento.dtStart];
Fecha_DTO *fechaEnd = [[Fecha_DTO alloc] initWithFecha:(NSDictionary *)evento.dtEnd];
// Format the dates to type NSDate
// Start Date
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyyMMdd'T'HHmmss"];
if (fechaStart.tzid == nil) {
[df setTimeZone: [NSTimeZone systemTimeZone]];
}else{
[df setTimeZone:[NSTimeZone timeZoneWithName:fechaStart.tzid]];
}
NSDate* parsedDateS = [df dateFromString: fechaStart.fecha];
// End Date
NSDateFormatter* df2 = [[NSDateFormatter alloc] init];
[df2 setDateFormat:#"yyyyMMdd'T'HHmmss"];
if (fechaEnd.tzid == nil) {
[df2 setTimeZone: [NSTimeZone systemTimeZone]];
}else{
[df2 setTimeZone:[NSTimeZone timeZoneWithName:fechaEnd.tzid]];
}
NSDate* parsedDateE = [df2 dateFromString: fechaEnd.fecha];
//rRules
NSString *rfc2445String = evento.rRule; // Usando la libreria EKRecurrenceRule+RRULE.m
EKRecurrenceRule *recurrenceRule;
if (![rfc2445String isEqualToString:#""]) {
recurrenceRule = [[EKRecurrenceRule alloc] initWithString:rfc2445String andTimezone:fechaStart.tzid];
// NSLog(#"RRule: %#", recurrenceRule);
}
if(parsedDateS!=nil){
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted) {
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = evento.summary;
event.notes = evento.description;
event.startDate = parsedDateS;
event.endDate = parsedDateE;
event.location = evento.location;
if (![rfc2445String isEqualToString:#""])
event.recurrenceRules = [NSArray arrayWithObject:recurrenceRule];
event.calendar = [eventStore calendarWithIdentifier: cal.calendarIdentifier];
//[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err = nil;
BOOL success = [eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
if(!success){
if (err) {
NSLog(#"Calendar was not set: %li %#", (long)err.code, err.description);
}
}else{
//NSLog(#"Added Event");
res = YES;
}
} else {
// code here for when the user does NOT allow your app to access the calendar
alerta = [[UIAlertView alloc]initWithTitle:AMLocalizedString(#"Error", #"")
message:AMLocalizedString(#"errorPermisosCal", #"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alerta show];
}
}];
}else{
NSLog(#"The start date is null");
}
df = nil;
df2 = nil;
}else{
alerta = [[UIAlertView alloc]initWithTitle:AMLocalizedString(#"Error", #"")
message:AMLocalizedString(#"VersionEvento", #"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alerta show];
}
return res;
}

Finally I have been able to perform the massive bulk of events without failures, I have modified the methods being as follows:
- (void) addCalendarEvents: (EKCalendar *) cal store: (EKEventStore *) eventStore {
if (!SYSTEM_VERSION_LESS_THAN(#"6.0")) {
// iOS 6 and later
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted) {
//se aƱade cada uno de los eventos
for (int i=0; i < [calendario.eventos count]; i++) {
#autoreleasepool {
NSDictionary * nextDict = [calendario.eventos objectAtIndex:i];
Evento_DTO * evento_dto = [[Evento_DTO alloc] initWithEventos:nextDict];
[self addEventCalendar: evento_dto calendar: cal.calendarIdentifier store: eventStore];
}
}
} else {
// code here for when the user does NOT allow your app to access the calendar
alerta = [[UIAlertView alloc]initWithTitle:AMLocalizedString(#"Error", #"")
message:AMLocalizedString(#"errorPermisosCal", #"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alerta show];
}
}];
}else{
alerta = [[UIAlertView alloc]initWithTitle:AMLocalizedString(#"Error", #"")
message:AMLocalizedString(#"Event version", #"")
delegate:self
cancelButtonTitle:#"OK"
otherButtonTitles:nil, nil];
[alerta show];
}
}
And the function that adds the event to the calendar is as follows:
-(void)addEventCalendar: (Evento_DTO *) evento calendar: (NSString *) cal store: (EKEventStore *) eventStore{
//Obtenemos las fechas del evento
Fecha_DTO *fechaStart = [[Fecha_DTO alloc] initWithFecha:(NSDictionary *)evento.dtStart];
Fecha_DTO *fechaEnd = [[Fecha_DTO alloc] initWithFecha:(NSDictionary *)evento.dtEnd];
// Format the dates to type NSDate
// Start Date
NSDateFormatter* df = [[NSDateFormatter alloc] init];
[df setDateFormat:#"yyyyMMdd'T'HHmmss"];
if (fechaStart.tzid == nil) {
[df setTimeZone: [NSTimeZone systemTimeZone]];
}else{
[df setTimeZone:[NSTimeZone timeZoneWithName:fechaStart.tzid]];
}
NSDate* parsedDateS = [df dateFromString: fechaStart.fecha];
// End Date
NSDateFormatter* df2 = [[NSDateFormatter alloc] init];
[df2 setDateFormat:#"yyyyMMdd'T'HHmmss"];
if (fechaEnd.tzid == nil) {
[df2 setTimeZone: [NSTimeZone systemTimeZone]];
}else{
[df2 setTimeZone:[NSTimeZone timeZoneWithName:fechaEnd.tzid]];
}
NSDate* parsedDateE = [df2 dateFromString: fechaEnd.fecha];
//rRules
NSString *rfc2445String = evento.rRule;
EKRecurrenceRule *recurrenceRule;
if (![rfc2445String isEqualToString:#""]) {
recurrenceRule = [[EKRecurrenceRule alloc] initWithString:rfc2445String andTimezone:fechaStart.tzid];
//NSLog(#"RRule: %#", recurrenceRule);
}
if(parsedDateS!=nil){
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title = evento.summary;
event.notes = evento.description;
event.location = evento.location;
event.startDate = parsedDateS;
event.endDate = parsedDateE;
if (![rfc2445String isEqualToString:#""])
event.recurrenceRules = [NSArray arrayWithObject:recurrenceRule];
event.calendar = [eventStore calendarWithIdentifier: cal];
NSError *err = nil;
BOOL success = [eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
if(!success){
if (err) {
NSLog(#"Calendar was not set: %li %#", (long)err.code, err.description);
}
}else{
NSLog(#"Added Event");
}
}else{
NSLog(#"The start date is null");
}
df = nil;
df2 = nil;
}
I hope it helps somebody.

Related

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];
}

Gamecenter Score Not Submitting Correct Score

When I test my game the score of my game ends in a time of 3.49 seconds, but in gamecenter the score that shows up in the leaderboards is 1:01:52.76. I think the problem is that i get a yellow flag that says incompatible integer to integer conversion assigning to int_64 (aka long long) from NSString. Here is the part of the code that shows the error.
- (IBAction)buttonPressed:(id)sender {
[self startTimer];
count--;
countLabel.text = [NSString stringWithFormat:#"Score\n%i", count];
// 2
if (count == 0) {
[self.stopWatchTimer invalidate];
timeLabel.hidden = YES;
// Create date from the elapsed time
NSDate *currentDate = [NSDate date];
NSTimeInterval timeInterval = [currentDate timeIntervalSinceDate:self.startDate];
NSDate *timerDate = [NSDate dateWithTimeIntervalSince1970:timeInterval];
// Create a date formatter
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"'Your time: 'ss.SSS"];
[dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0.0]];
// Format the elapsed time and set it to the label
NSString *timeString = [dateFormatter stringFromDate:timerDate];
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Time is up!"
message: timeString
delegate:self
cancelButtonTitle:#"Play Again"
otherButtonTitles:#"Level Select",nil];
[alert show];
if (count == 0) {
GKScore *scoreReporter = [[GKScore alloc] initWithLeaderboardIdentifier:#"tap_novice"];
scoreReporter.value = timeString;
scoreReporter.context = 0;
NSArray *scores = #[scoreReporter];
[GKScore reportScores:#[scoreReporter] withCompletionHandler:^(NSError *error) {
if (error == nil) {
NSLog(#"Score reported successfully!");
} else {
NSLog(#"Unable to report score!");
}
}];
}
}
}
#end
Instead of the current line you have:
scoreReporter.value = timeString;
You should use:
int64_t timeAsInt = [timeString longLongValue];
scoreReporter.value = timeAsInt;
See the following link

EKEventStore new event creation doesn't seem to work and there is no error description either

I am using the below two methods to create Events in the device calendar, Events is my managedObject class.
+ (void)createCalendarEvents:(NSArray *)eventsArray
{
EKEventStore *eventStore = [[SharedLoader sharedInstance] eventStore];
NSLog(#"eventStore: %#",eventStore);
BOOL needsToRequestAccessToEventStore = NO; // iOS 5 behavior
if ([[EKEventStore class] respondsToSelector:#selector(authorizationStatusForEntityType:)])
needsToRequestAccessToEventStore = ([EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent] == EKAuthorizationStatusNotDetermined);
if (needsToRequestAccessToEventStore) {
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted) {
dispatch_async(dispatch_get_main_queue(), ^{
for(Events *eventObject in eventsArray)
[self addEventToCalendar:eventObject forEventStoreObject:eventStore];
NSError *commitError;
if([eventStore commit:&commitError])
{
NSLog(#"Events commited to device calendar");
}
else
{
NSLog(#"Events could not be commited to device calendar: %#",[commitError localizedDescription]);
}
});
}
}];
}
else {
dispatch_async(dispatch_get_main_queue(), ^{
for(Events *eventObject in eventsArray)
[self addEventToCalendar:eventObject forEventStoreObject:eventStore];
NSError *commitError;
if([eventStore commit:&commitError])
{
NSLog(#"Events commited to device calendar");
}
else
{
NSLog(#"Events could not be commited to device calendar: %#",[commitError localizedDescription]);
}
});
}
}
+ (BOOL)addEventToCalendar:(Events *)eventObject forEventStoreObject:(EKEventStore *)eventStore
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[dateFormatter setLocale:[NSLocale currentLocale]];
NSString *date =[NSString stringWithFormat:#"%#", eventObject.eventStartDate];
NSPredicate *predicateForEventsOndate = [eventStore predicateForEventsWithStartDate: eventObject.eventStartDate endDate:[[NSDate alloc] initWithTimeInterval:600 sinceDate:[dateFormatter dateFromString:date]] calendars:nil]; // nil will search through all calendars
NSArray *eventsOnDate = [eventStore eventsMatchingPredicate:predicateForEventsOndate];
BOOL eventExists = NO;
EKEvent *existingEvent = nil;
for (EKEvent *eventToCheck in eventsOnDate) {
if ([eventToCheck.title isEqualToString:eventObject.eventTitle]) {
eventExists = YES;
existingEvent=eventToCheck;
break;
}
}
if (eventExists == NO) {
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title =[NSString stringWithFormat:#"%#",eventObject.eventTitle];
NSLog(#"calendar event: %#", event.title);
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[tempFormatter setLocale:[NSLocale currentLocale]];
NSString *dateandtime =[NSString stringWithFormat:#"%#",eventObject.eventStartDate];
NSLog(#"dateandtime: %#",dateandtime);
NSString *dateandtimeend =[NSString stringWithFormat:#"%#",eventObject.eventEndDate];
NSLog(#"dateandtime: %#",dateandtimeend);
event.location = [NSString stringWithFormat:#"%#",eventObject.eventVenue];;
event.startDate =[tempFormatter dateFromString:dateandtime];
event.endDate = [tempFormatter dateFromString:dateandtimeend];
event.notes =eventObject.eventPurpose;
/*[event addAlarm:[EKAlarm alarmWithAbsoluteDate:event.startDate]];
[event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -60.0f * 24]];
[event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -15.0f]];*/
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
if([eventStore saveEvent:event span:EKSpanThisEvent error:&err])
{
NSLog(#"New Event Saved Successfully");
return YES;
}
else
{
NSLog(#"New Event could not be saved: %# %#",[err localizedDescription],err);
return NO;
}
}
else
{
existingEvent.title =[NSString stringWithFormat:#"%#",eventObject.eventTitle];
NSLog(#"calendar event: %#", existingEvent.title);
NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
[tempFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
[tempFormatter setLocale:[NSLocale currentLocale]];
NSString *dateandtime =[NSString stringWithFormat:#"%#",eventObject.eventStartDate];
NSLog(#"dateandtime: %#",dateandtime);
NSString *dateandtimeend =[NSString stringWithFormat:#"%#",eventObject.eventEndDate];
NSLog(#"dateandtime: %#",dateandtimeend);
existingEvent.location = [NSString stringWithFormat:#"%#",eventObject.eventVenue];;
existingEvent.startDate =[tempFormatter dateFromString:dateandtime];
existingEvent.endDate = [tempFormatter dateFromString:dateandtimeend];
existingEvent.notes =eventObject.eventPurpose;
/*[existingEvent addAlarm:[EKAlarm alarmWithAbsoluteDate:existingEvent.startDate]];
[existingEvent addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -60.0f * 24]];
[existingEvent addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -15.0f]];*/
[existingEvent setCalendar:[eventStore defaultCalendarForNewEvents]];
NSError *err;
if([eventStore saveEvent:existingEvent span:EKSpanThisEvent error:&err])
{
NSLog(#"Old Event Updated & Saved Successfully");
return YES;
}
else
{
NSLog(#"Existing Event could not be saved: %#",[err localizedDescription]);
return NO;
}
}
}
My events are saved successfully and also I see them on the device calendar but the events are in 2001 and the events disappear after some doing some scroll in the list of events. Need help in this.

Setting Calendar Event From Date Picker

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];

Resources