Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Add Event to calendar in xcode iOS

Hy

I have this code for adding Events to calendar but it does not add.

-(void)event
{
    EKEventStore *eventStore = [[EKEventStore alloc] init];

    EKEvent *event  = [EKEvent eventWithEventStore:eventStore];
    event.title     = @"Event";


    NSDateFormatter *tempFormatter = [[NSDateFormatter alloc]init];
    [tempFormatter setDateFormat:@"dd.MM.yyyy HH:mm"];


    NSString *dateandtime =[NSString stringWithFormat:@"%@%@%@",datestring,@" ",starttimestring];
    NSString *dateandtimeend =[NSString stringWithFormat:@"%@%@%@",datestring,@" ",endtimestring];



    event.startDate = [tempFormatter dateFromString:dateandtime];
    event.endDate = [tempFormatter dateFromString:dateandtimeend];


    [event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -60.0f * 24]];
    [event addAlarm:[EKAlarm alarmWithRelativeOffset:60.0f * -15.0f]];

    [event setCalendar:[eventStore defaultCalendarForNewEvents]];
    NSError *err;
    [eventStore saveEvent:event span:EKSpanThisEvent error:&err];
}

From the XML I get the date and time in this format:

datestring: 28.10.2012

starttimestring: 15:00

like image 359
WildWorld Avatar asked Oct 26 '12 07:10

WildWorld


1 Answers

Are you on the iOS 6 simulator or on a device with iOS 6? If so, you need to ask the user for permission to use the event store before you can save items to it.

Basically, if the requestAccessToEntityType:completion: selector is available on your event store object, you call that method and provide a block of code that is executed when the user grants permission, and you would then do your event saving in that block.

First add the EventKit framework to your project and don't forget to include the import:

#import <EventKit/EventKit.h>

Here is a code snippet that I used that worked for me:

EKEventStore *eventStore = [[EKEventStore alloc] init];
if ([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)])
{
    // the selector is available, so we must be on iOS 6 or newer
    [eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        dispatch_async(dispatch_get_main_queue(), ^{
            if (error)
            {
                // display error message here
            }
            else if (!granted)
            {
                // display access denied error message here
            }
            else
            {
                // access granted
                // ***** do the important stuff here *****
            }
        });
    }];
}
else
{
    // this code runs in iOS 4 or iOS 5
    // ***** do the important stuff here *****
}

[eventStore release];

Here is a blog post that I did on this subject:

http://www.dosomethinghere.com/2012/10/08/ios-6-calendar-and-address-book-issues/

like image 98
BP. Avatar answered Oct 01 '22 10:10

BP.