Добавить событие в календарь в Xcode iOS

Hy

У меня есть этот код для добавления событий в календарь, но это не добавит.

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

из XML я получаю дату и время в следующем формате:

дату: 28.10.2012

starttimestring: 15:00

2 ответов


вы находитесь на симуляторе iOS 6 или на устройстве с iOS 6? Если это так, перед сохранением элементов в хранилище событий необходимо запросить у пользователя разрешение на использование хранилища событий.

в основном, если requestaccesstoentitytype: completion: selector доступен в вашем объекте хранилища событий, вы вызываете этот метод и предоставляете блок кода, который выполняется, когда пользователь предоставляет разрешение, и затем вы бы сделали сохранение события в этом блоке.

Сначала добавьте фреймворк EventKit к вашему проекту и не забудьте включить импорт:

#import <EventKit/EventKit.h>

вот фрагмент кода, который я использовал, что работал для меня:

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

вот сообщение в блоге, которое я сделал на эту тему:

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


1) добавить Eventkit Framework и #import <EventKit/EventKit.h>

2)

 -(void)syncWithCalendar {
    EKEventStore *store = [EKEventStore new];
    [store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
        if (!granted) { return; }
        EKEvent *event = [EKEvent eventWithEventStore:store];
        event.title = @"Event Title Testing"; //give event title you want
        event.startDate = [NSDate date];
        event.endDate = [event.startDate dateByAddingTimeInterval:60*60];
        event.calendar = [store defaultCalendarForNewEvents];
        NSError *err = nil;
        [store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
    }];
}

3) вызов функции

[self syncWithCalendar];