Custom Calender & Save Data
1) Import Following Framework :
- EventKit.Framework
************** Create NSObject File And Write Following Coding **********
2) Create Custom NSObject File :
MyCalendar.h :
#import <Foundation/Foundation.h>
@interface MyCalendar : NSObject
+ (void)requestAccess:(void (^)(BOOL granted, NSError *error))success;
+ (BOOL)addEventAt:(NSDate*)eventDate withEndDate:(NSDate*)endDate withTitle:(NSString*)title inLocation:(NSString*)location latitude: (NSString*)latval longitude:(NSString*)longval ;
+ (BOOL)removeEventAt:(NSDate*)eventDate withEndDate:(NSDate*)endDate withTitle:(NSString*)title inLocation:(NSString*)location;
@end
MyCalendar.m :
#import "MyCalendar.h"
#import <EventKit/EventKit.h>
static EKEventStore *eventStore = nil;
static NSString *savedEventId;
@implementation MyCalendar
+ (void)requestAccess:(void (^)(BOOL granted, NSError *error))callback;
{
if (eventStore == nil) {
eventStore = [[EKEventStore alloc] init];
}
// request permissions
[eventStore requestAccessToEntityType:EKEntityTypeEvent completion:callback];
}
+ (BOOL)addEventAt:(NSDate*)eventDate withEndDate:(NSDate*)endDate withTitle:(NSString*)title inLocation:(NSString*)location latitude: (NSString*)latval longitude:(NSString*)longval ;
{
EKEvent *event = [EKEvent eventWithEventStore:eventStore];
EKCalendar *calendar = nil;
NSString *calendarIdentifier = [[NSUserDefaults standardUserDefaults] valueForKey:@"my_calendar_identifier"];
// when identifier exists, my calendar probably already exists
// note that user can delete my calendar. In that case I have to create it again.
if (calendarIdentifier) {
calendar = [eventStore calendarWithIdentifier:calendarIdentifier];
}
// calendar doesn't exist, create it and save it's identifier
if (!calendar) {
calendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:eventStore];
// set calendar name. This is what users will see in their Calendar app
[calendar setTitle:@"Town Post"];
// find appropriate source type. I'm interested only in local calendars but
// there are also calendars in iCloud, MS Exchange, ...
// look for EKSourceType in manual for more options
/* for (EKSource *s in eventStore.sources) {
if (s.sourceType == EKSourceTypeLocal) {
calendar.source = s;
break;
}
}*/
if (calendar.source == nil)
{
for (EKSource *source in eventStore.sources)
{
if (source.sourceType == EKSourceTypeCalDAV && [source.title isEqualToString:@"iCloud"])
{
calendar.source = source;
break;
}
if (source.sourceType == EKSourceTypeLocal)
{
calendar.source = source;
break;
}
}
}
// save this in NSUserDefaults data for retrieval later
NSString *calendarIdentifier = [calendar calendarIdentifier];
NSError *error = nil;
BOOL saved = [eventStore saveCalendar:calendar commit:YES error:&error];
if (saved) {
// saved successfuly, store it's identifier in NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:calendarIdentifier forKey:@"my_calendar_identifier"];
} else {
// unable to save calendar
return NO;
}
}
// this shouldn't happen
if (!calendar) {
return NO;
}
// assign basic information to the event; location is optional
event.calendar = calendar;
event.location = location;
event.title = title;
// set the start date to the current date/time and the event duration to two hours
NSDate *startDate = eventDate;
event.startDate = startDate;
event.endDate = endDate;
//event.endDate = [startDate dateByAddingTimeInterval:3600 * 2];
EKStructuredLocation* structuredLocation = [EKStructuredLocation locationWithTitle:location]; // locationWithTitle has the same behavior as event.location
CLLocation *mylocation = [[CLLocation alloc] initWithLatitude:[latval floatValue] longitude:[longval floatValue]];
structuredLocation.geoLocation = mylocation;
[event setValue:structuredLocation forKey:@"structuredLocation"];
NSError *error = nil;
// save event to the callendar
BOOL result = [eventStore saveEvent:event span:EKSpanThisEvent commit:YES error:&error];
if (result) {
if ([event respondsToSelector:@selector(calendarItemIdentifier)]) {
[[NSUserDefaults standardUserDefaults] setObject:event.eventIdentifier forKey:title];
NSLog(@"Event ID: %@",event.calendarItemIdentifier);
}
return YES;
} else {
// [[NSUserDefaults standardUserDefaults] setObject:event.UUID forKey:@"eventid"];
// unable to save event to the calendar
return NO;
}
}
+ (BOOL)removeEventAt:(NSDate*)eventDate withEndDate:(NSDate*)endDate withTitle:(NSString*)title inLocation:(NSString*)location
{
EKEventStore *eventStore = [[EKEventStore alloc] init];
NSLog(@"Event ID: %@",[[NSUserDefaults standardUserDefaults] objectForKey:title]);
BOOL result;
NSError* err = nil;
//[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
// if (!granted) return;
//EKEvent* eventToRemove = [eventStore eventWithIdentifier:event.title];
EKEvent *existingEvent = [eventStore eventWithIdentifier:[[NSUserDefaults standardUserDefaults] objectForKey:title]];
if (existingEvent != nil) {
result = [eventStore removeEvent:existingEvent span:EKSpanThisEvent commit:YES error:&err];
}
if (result) {
[[NSUserDefaults standardUserDefaults] removeObjectForKey:title];
return YES;
} else {
NSLog(@"Error unsave event: %@", err);
// unable to save event to the calendar
return NO;
}
// }];
//EKEvent *event = [EKEvent eventWithEventStore:eventStore];
// EKEventStore *store = [[EKEventStore alloc] init];
/* EKEvent *event = [EKEvent eventWithEventStore:eventStore];
// set the start date to the current date/time and the event duration to two hours
NSDate *startDate = eventDate;
event.startDate = startDate;
event.endDate = endDate;
//event.endDate = [startDate dateByAddingTimeInterval:3600 * 2];
NSError *error = nil;
// save event to the callendar
BOOL result = [eventStore removeEvent:event span:EKSpanThisEvent commit:YES error:&error];
if (result) {
return YES;
} else {
// NSLog(@"Error saving event: %@", error);
// unable to save event to the calendar
return NO;
}*/
}
@end
3) Use This Custom NSObject File In ViewController :
- Simply Use This File At Any ViewController Using Below Coding :-
#import "MyCalendar.h"
-(NSDate *)setDateManually:(NSString *)dateStr time:(NSString *)time
{
NSString *temp = [NSString stringWithFormat:@"%@" , dateStr] ;
NSRange stringRange = {0, MIN([temp length], 10)};
stringRange = [temp rangeOfComposedCharacterSequencesForRange:stringRange];
NSString *shortString = [temp substringWithRange:stringRange];
NSDateFormatter* gmtDf = [[NSDateFormatter alloc] init] ;
[gmtDf setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
[gmtDf setDateFormat:@"yyyy-MM-dd"];
NSDate* gmtDate = [gmtDf dateFromString:shortString];
NSRange stringRange1 = {0, MIN([time length], 5)};
stringRange1 = [time rangeOfComposedCharacterSequencesForRange:stringRange1];
NSString *shortString1 = [time substringWithRange:stringRange1];
NSString *hourStr = [shortString1 componentsSeparatedByString:@":"][0];
NSString *minutesStr = [shortString1 componentsSeparatedByString:@":"][1];
NSString *timeSpecific = [time substringFromIndex:[time length] - 2]; //// AM , PM
NSInteger hour ;
NSInteger minutes ;
if([timeSpecific isEqualToString:@"am"])
{
hour = [hourStr intValue];
minutes = [minutesStr intValue];
}
else
{
hour = 12 + [hourStr intValue];
minutes = [minutesStr intValue];
}
NSCalendar* usCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian] ;
[usCalendar setTimeZone:[NSTimeZone timeZoneWithName:@"America/New_York"]];
NSDate *d = [usCalendar dateBySettingHour:hour minute:minutes second:0 ofDate:gmtDate options:0];
NSLog(@"date here : %@" , d) ;
return d ;
}
************** Add Event To Calender **********
NSDate *startDate = [self setDateManually:_startDateForCalender time:_startTimeForCalender] ;
NSDate *endDate = [self setDateManually:_endDateForCalender time:_endTimeForCalender] ;
[MyCalendar requestAccess:^(BOOL granted, NSError *error) {
if (granted) {
BOOL result = [MyCalendar addEventAt:startDate withEndDate:endDate withTitle:_selectedEventName inLocation:_selectedEventLocation latitude:_selectedEventLatitude longitude:_selectedEventLongitude];
if (result) {
// added to calendar
} else {
// unable to create event/calendar
}
} else {
// you don't have permissions to access calendars
}
}];
************** Remove Event From Calender **********
NSDate *startDate = [self setDateManually:_startDateForCalender time:_startTimeForCalender] ;
NSDate *endDate = [self setDateManually:_endDateForCalender time:_endTimeForCalender] ;
[MyCalendar requestAccess:^(BOOL granted, NSError *error) {
if (granted) {
BOOL result = [MyCalendar removeEventAt:startDate withEndDate:endDate withTitle:_selectedEventName inLocation:_selectedEventLocation];
//[MyCalendar removeEventAt:startDate withEndDate:endDate withTitle:_selectedEventName inLocation:_selectedEventLocation];
if (result) {
// added to calendar
} else {
// unable to create event/calendar
}
} else {
// you don't have permissions to access calendars
}
}];
