Добавить событие в календарь в xcode iOS - программирование

Добавить событие в календарь в 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 я получаю дату и время в этом формате:

datestring: 28.10.2012

starttimestring: 15:00

4b9b3361

Ответ 1

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

В принципе, если в объекте хранилища событий доступен requestAccessToEntityType: complete: 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/

Ответ 2

1) добавьте инфраструктуру Eventkit и #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];