- (void)syncWithCalendar
{
NSMutableDictionary *dictionary = [util readPListData];
NSMutableArray *courses = [util getCourses];
__block NSMutableArray *lessons;
__block NSMutableDictionary *lesson;
NSString *studentID = [util getProgramDetails].studentId;
NSString *programName = [util getProgramDetails].programName;
__block NSString *startDateString = #"", *endDateString = #"";
NSDateFormatter *formatter;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy HH:mm:ss"];
[formatter setDateFormat:#"MM/dd/yyyy"];
NSString *currentDateString = [NSString stringWithFormat:#"%# 09:00:00", [formatter stringFromDate:[NSDate date]]];
[formatter setDateFormat:#"MM/dd/yyyy HH:mm:ss"];
NSDate *currentDate = [formatter dateFromString:currentDateString];
self.eventstore = [[EKEventStore alloc] init];
[self.eventstore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error)
{
if (granted) {
NSLog(#"calendar access granted");
for (int i=0; i<[courses count]; i++)
{
lessons = [[courses objectAtIndex:i] objectForKey:#"lessons"];
for (int j=0; j<[lessons count]; j++)
{
lesson = [lessons objectAtIndex:j];
NSString *title = nil;
title = [NSString stringWithFormat:#"%# %#-Complete %# lesson",studentID,programName,[lesson objectForKey:#"lesson-name"]];
startDateString = [NSString stringWithFormat:#"%# %#", [lesson objectForKey:#"exam-date"], #"09:00:00"];
endDateString = [NSString stringWithFormat:#"%# %#", [lesson objectForKey:#"exam-date"], #"18:00:00"];
if (!([startDateString isEqualToString:#""] && [endDateString isEqualToString:#""]))
{
EKEvent *event = [EKEvent eventWithEventStore:self.eventstore];
event.title=title;
event.startDate = [formatter dateFromString:startDateString];
event.endDate = [formatter dateFromString:endDateString];
event.allDay = NO;
[event setCalendar:[self.eventstore defaultCalendarForNewEvents]];
NSError *err = nil;
[self.eventstore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
//[self.eventstore saveEvent:event span:EKSpanThisEvent error:&err];
if (err) {
NSLog(#"event not saved .. error = %#",err);
} else {
NSLog(#"event added successfully");
}
}
} // lessons for loop
} // courses for loop
} else {
NSLog(#"Access not granted");
}
}];
[self.eventstore release];
[formatter release];
}
After events gets successfully added it shows:
"Received Memory Warning. Terminating in response to SpringBoard's termination"
and the app terminates. This is happening in iOS 7 device. I haven't checked it yet in iOS 6 and below. The code works fine if there are only a few events saved (30 or less) but it shows memory issue for 80 events or more on saving.
Finally I found the answer to my question. I would like to share my solution so that it can help others ....
I was specially getting the crash in iOS 7 and it was because of the below line
// wrong
[self.eventstore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
The correct way to save event: (Note: I didn't require event identifier for my case)
// correct
[self.eventstore saveEvent:event span:EKSpanThisEvent commit:NO error:&err];
and then use
[self.eventstore commit:NULL]
after all the events are saved.
This stopped the crash in my case.
Switching to ARC may solve the problem with memory but problems may still occur with large amount of data.
Try using #autorelease pools inside for loop as in example
for (int i=0; i<[courses count]; i++)
{
#autoreleasepool {
lessons = [[courses objectAtIndex:i] objectForKey:#"lessons"];
for (int j=0; j<[lessons count]; j++)
{
lesson = [lessons objectAtIndex:j];
NSString *title = nil;
title = [NSString stringWithFormat:#"%# %#-Complete %# lesson",studentID,programName,[lesson objectForKey:#"lesson-name"]];
startDateString = [NSString stringWithFormat:#"%# %#", [lesson objectForKey:#"exam-date"], #"09:00:00"];
endDateString = [NSString stringWithFormat:#"%# %#", [lesson objectForKey:#"exam-date"], #"18:00:00"];
if (!([startDateString isEqualToString:#""] && [endDateString isEqualToString:#""]))
{
EKEvent *event = [EKEvent eventWithEventStore:self.eventstore];
event.title=title;
event.startDate = [formatter dateFromString:startDateString];
event.endDate = [formatter dateFromString:endDateString];
event.allDay = NO;
[event setCalendar:[self.eventstore defaultCalendarForNewEvents]];
NSError *err = nil;
[self.eventstore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
//[self.eventstore saveEvent:event span:EKSpanThisEvent error:&err];
if (err) {
NSLog(#"event not saved .. error = %#",err);
} else {
NSLog(#"event added successfully");
}
}
} // lessons for loop
}//autoreleasepool
} // courses for loop
This way each for loop step will release all autorelease objects.
#upendar I also have same scenario but i am split into small chunks, I.E. Like if you have 80 events to sync take 20-20 and pause 2-5sec. between them.
autoreleasepool is good to use, But it Calendar took too much memory to execute. It will take more then 100% some time.
I bared with this issue. Really interesting one!!!
Related
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.
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
I am making a call to syncWithCalendar and after events are successfully added, I get low memory warning and app terminates with "Received Low Memory" warning. The events generated and saved in calendar are more than 50. I tried using instruments but I am not able to find the code where memory leak occurs and also through live bytes that show in instruments I am not able to track the code that is causing the leak. Can anyone please help me solve this issue.
- (void)syncWithCalendar
{
#autoreleasepool {
[self deleteEventsIfExist];
NSMutableDictionary *dictionary = [util readPListData];
NSMutableArray *courses = [util getCourses];
__block NSMutableArray *lessons;
__block NSMutableDictionary *lesson;
NSString *studentID = [util getProgramDetails].studentId;
NSString *programName = [util getProgramDetails].programName;
double offset[] = {0, 0, -300, -900, -1800, -3600, -7200, -86400, -172800};
__block NSString *startDateString = #"", *endDateString = #"";
NSTimeInterval relativeOffsetValue = 0;
int index = [[dictionary objectForKey:#"event-alert-option"] intValue];
relativeOffsetValue = offset[index];
NSDateFormatter *formatter;
formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MM/dd/yyyy HH:mm:ss"];
[formatter setDateFormat:#"MM/dd/yyyy"];
NSString *currentDateString = [NSString stringWithFormat:#"%# 09:00:00", [formatter stringFromDate:[NSDate date]]];
[formatter setDateFormat:#"MM/dd/yyyy HH:mm:ss"];
NSDate *currentDate = [formatter dateFromString:currentDateString];
EKEventStore *eventStore = [[EKEventStore alloc] init];
if([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)]) {
// iOS 6 and later
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (granted){
//---- codes here when user allow your app to access theirs' calendar.
dispatch_async(dispatch_get_main_queue(), ^{
// Event creation code here.
for (int i=0; i<[courses count]; i++)
{
#autoreleasepool {
lessons = [[courses objectAtIndex:i] objectForKey:#"lessons"];
for (int j=0; j<[lessons count]; j++)
{
#autoreleasepool {
lesson = [lessons objectAtIndex:j];
NSString *title = nil;
title = [NSString stringWithFormat:#"%# %#-Complete %# lesson",studentID,programName,[lesson objectForKey:#"lesson-name"]];
if ([[lesson objectForKey:#"actual-exam-date"] isEqualToString:#"00/00/0000"])
{
startDateString = [NSString stringWithFormat:#"%# %#", [lesson objectForKey:#"plan-exam-date"], #"09:00:00"];
endDateString = [NSString stringWithFormat:#"%# %#", [lesson objectForKey:#"plan-exam-date"], #"18:00:00"];
}
else
{
if ([[lesson objectForKey:#"retake-actual-date"] isEqualToString:#"00/00/0000"])
{
startDateString = [NSString stringWithFormat:#"%# %#", [lesson objectForKey:#"retake-plan-date"], #"09:00:00"];
endDateString = [NSString stringWithFormat:#"%# %#", [lesson objectForKey:#"retake-plan-date"], #"18:00:00"];
}
}
if (!([startDateString isEqualToString:#""] && [endDateString isEqualToString:#""]))
{
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
event.title=title;
event.startDate = [formatter dateFromString:startDateString];
event.endDate = [formatter dateFromString:endDateString];
event.allDay = NO;
if (index != 0)
{
event.alarms = [NSArray arrayWithObjects:[EKAlarm alarmWithRelativeOffset:relativeOffsetValue], nil];
}
[event setCalendar:[eventStore defaultCalendarForNewEvents]];
// Compare current date to event start date, if start date has been passed then preventing to sync with calendar
NSComparisonResult result = [event.startDate compare:currentDate];
if (result != NSOrderedAscending)
{
NSError *err = nil;
[eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
if (err) {
NSLog(#"event not saved .. error = %#",err);
} else {
NSLog(#"event added successfully");
}
}
}
} // autoreleasepool
} // lessons for loop
} // autoreleasepool
} // courses for loop
[self hideModal];
});
}else
{
//----- codes here when user NOT allow your app to access the calendar.
// [self performSelectorOnMainThread:#selector(hideModal) withObject:nil waitUntilDone:NO];
}
}];
} else {
// sync calendar for <iOS6
}
} // autoreleasepool
}
- (void)deleteEventsIfExist
{
#autoreleasepool {
NSMutableArray *courses = [util getCourses];
__block NSMutableArray *lessons;
__block NSMutableDictionary *lesson;
NSString *studentID = [util getProgramDetails].studentId;
NSString *programName = [util getProgramDetails].programName;
EKEventStore* store = [[EKEventStore alloc] init];
dispatch_async(dispatch_get_main_queue(), ^{
// Event creation code here.
NSDate* endDate = [NSDate dateWithTimeIntervalSinceNow:[[NSDate distantFuture] timeIntervalSinceReferenceDate]];
NSPredicate *fetchCalendarEvents = [store predicateForEventsWithStartDate:[NSDate date] endDate:endDate calendars:store.calendars];
NSArray *allEvents = [store eventsMatchingPredicate:fetchCalendarEvents];
for (int i=0; i<[courses count]; i++)
{
#autoreleasepool {
lessons = [[courses objectAtIndex:i] objectForKey:#"lessons"];
for (int j=0; j<[lessons count]; j++)
{
#autoreleasepool {
lesson = [lessons objectAtIndex:j];
NSString *oldEventSubtitle = [NSString stringWithFormat:#"%# %#-Complete %# lesson",studentID,programName,[lesson objectForKey:#"lesson-name"]];
for (EKEvent *e in allEvents)
{
if ( [oldEventSubtitle isEqualToString:e.title])
{
NSError* error = nil;
[store removeEvent:e span:EKSpanThisEvent commit:YES error:&error];
NSLog(#"deleting events");
}
}
} // autoreleasepool
} // lessons
} // autoreleasepool
} // courses
});
} // autoreleasepool
}
It's a rough guess, but it seems the asynchronous invocations may lead to troubles.
In order to test this, just use dispatch_sync instead of dispatch_async and examine the memory consumption. If this leads to an improvement, then a solution is in sight, which involves to re-factor your current asynchronous "parallel" approach and turn it into an appropriate asynchronous "serial" approach or an complete synchronous approach.
This may also require to "serialize" all invocations of this asynchronous method:
[eventStore requestAccessToEntityType:EKEntityTypeEvent
completion:^(BOOL granted, NSError *error) {
...
}]
This is how I made a call to syncWithCalendar function
if([eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)]) {
// iOS 6 and later
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted,
NSError *error) {
if (granted){
dispatch_async(dispatch_get_main_queue(), ^{
[self syncWithCalendar];
});
} else {
// calendar access not granted
}
}];
}
And in syncWithCalendar function everything remains same except the line of code that
was creating the crash/memory issue. Below is the incorrect line of code that I was
using earlier
// wrong
[self.eventstore saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
The correct way to save event: (Note: I didn't require event identifier in my case)
// correct
[self.eventstore saveEvent:event span:EKSpanThisEvent commit:NO error:&err];
and then use [self.eventstore commit:NULL] after all the events are saved. This stopped the crash in my case. Hope this post will
help other get the solution. Thanks !!!!
You need to clear the cache when you are receiving memory warning, use this method it will help you.
-(void)applicationDidReceiveMemoryWarning:(UIApplication *)application {
[[NSURLCache sharedURLCache] removeAllCachedResponses];
}
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.
My EKEvent is not saving in my iphone 5 ios 6.1 but its saved on my ipod 6.0. and When I update my event and save it , the event is deleted.
Please help me fix it. Its it a ios bug? or just in the code?
this is my code:
- (IBAction)submitButtonPressed:(id)sender {
if (!self.eventStore) {
self.eventStore = [[[EKEventStore alloc]init]autorelease];
}
if (!self.event) {
self.event = [EKEvent eventWithEventStore:self.eventStore];
}
if ([self.eventStore respondsToSelector:#selector(requestAccessToEntityType:completion:)])
{
// the selector is available, so we must be on iOS 6 or newer
[self.eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
dispatch_async(dispatch_get_main_queue(), ^{
if (error)
{
NSLog(#"error: %#",error);
// display error message here
}
else if (!granted)
{
NSLog(#"error: Access Denied");
// display access denied error message here
}
else
{
// access granted
if (!self.isEditing) {
[self.event setCalendar:[self.eventStore defaultCalendarForNewEvents]];
}
[self sendEvent];
}
});
}];
}
else
{
[self.event setCalendar:[self.eventStore defaultCalendarForNewEvents]];
[self sendEvent];
}
}
-(void)sendEvent {
self.event.title = self.eventModel.eventName;
self.event.location = self.eventModel.eventLocation;
self.event.notes = self.eventModel.eventDescription;
self.eventModel.date = self.datePicked;
NSString *fromTime = [NSString string];
NSString *toTime = [NSString string];
if (self.eventModel.fromTime) {
fromTime = [NSString stringWithFormat:#"%#:%#",[ self.eventModel.fromTime objectForKey:#"hour"],[self.eventModel.fromTime objectForKey:#"minute"]];
}
if (self.eventModel.toTime) {
toTime = [NSString stringWithFormat:#"%#:%#",[ self.eventModel.toTime objectForKey:#"hour"],[self.eventModel.toTime objectForKey:#"minute"]];
}
//set start date and time
NSDateFormatter *tempFormatter = [[[NSDateFormatter alloc]init] autorelease];
[tempFormatter setDateFormat:#"yyyy-MM-dd hh:mm"];
NSString *dateandtime =[NSString stringWithFormat:#"%#%#%#",self.eventModel.fromDate,#" ", fromTime];
//set end date and time
NSDateFormatter *tempFormatterTo = [[[NSDateFormatter alloc]init] autorelease];
[tempFormatterTo setDateFormat:#"yyyy-MM-dd hh:mm"];
NSString *dateandtimeTo =[NSString stringWithFormat:#"%#%#%#",self.eventModel.toDate,#" ", toTime];
self.event.startDate = [tempFormatter dateFromString:dateandtime];
self.event.endDate = [tempFormatterTo dateFromString:dateandtimeTo];
self.event.allDay = self.eventModel.allDay;
[self.eventStore saveEvent:self.event span:EKSpanFutureEvents error:&err];
}