iOS--日历事件的获取和添加

日历添加事件

EKEventStore* eventStore = [[EKEventStore alloc] init];//获取日历类
    EKEvent *event  = [EKEvent eventWithEventStore:eventStore];//日历类事件
    NSDate *startDate = [[NSDate alloc] init];
    NSDate *endDate  = [[NSDate alloc] init];
    event.title     = @"New event test";
    event.startDate = startDate;//开始日期
    event.endDate   = endDate;//结束日期
    event.location = @"浙江";//位置
    event.allDay = YES;//是否是全天
    [event setCalendar:[eventStore defaultCalendarForNewEvents]];
    [event addAlarm:[EKAlarm alarmWithRelativeOffset:-30.0f]];
    [event addAlarm:[EKAlarm alarmWithRelativeOffset:-15.0f]];
    __block NSError *err;
    //ios 6之后
    if([eventStore respondsToSelector:@selector(requestAccessToEntityType:completion:)]) {
        [eventStore requestAccessToEntityType:EKEntityTypeEvent
                                   completion:^(BOOL granted, NSError *error) {
                                       dispatch_async(dispatch_get_main_queue(), ^{
                                           if (granted) {
                                               [eventStore saveEvent:event span:EKSpanFutureEvents commit:YES error:&err];
                                           } else {
                                               NSLog(@"不允许访问日历");
                                           }
                                       });
                                   }];
    } else {
        //ios4,5
        [eventStore saveEvent:event span:EKSpanThisEvent error:&err];
    }

获取日历中的事件

EKEventStore* eventStore = [[EKEventStore alloc] init];
    NSDate* ssdate = [NSDate dateWithTimeIntervalSinceNow:-3600*24*90];//事件段,开始时间
    NSDate* ssend = [NSDate dateWithTimeIntervalSinceNow:3600*24*90];//结束时间,取中间
    NSPredicate* predicate = [eventStore predicateForEventsWithStartDate:ssdate
                                                                 endDate:ssend
                                                               calendars:nil];//谓语获取,一种搜索方法
    NSArray* events = [eventStore eventsMatchingPredicate:predicate];//数组里面就是时间段中的EKEvent事件数组

    for (EKEvent *event in events) {
        NSLog(@"=================================================================");
        NSLog(@"%@", event.title);
        NSLog(@"%@", event.startDate);
        NSLog(@"=================================================================");
    }
posted @ 2015-07-30 20:48  AbeDay  阅读(775)  评论(0编辑  收藏  举报