将事件添加到日历中的特定日期

时间:2015-03-06 19:30:38

标签: ios swift

我想在iOS中将日历添加到日历中。我在字符串中有活动日期。

如果event.startDate = eventToCalDate和event.endDate = eventToCalDate,则此代码不会添加事件。但是如果event.startDate = NSDate()和event.endDate = NSDate()

它会很好用
eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: {
        granted, error in
        if (granted) && (error == nil) {
            println("granted \(granted)")
            println("error  \(error)")

            self.eventTechDate = "2015-03-06 18:58:13 +0000";
            var tempDateFormatter = NSDateFormatter()
            tempDateFormatter.dateFormat = "YYYY-MM-DD HH:mm:ss Z"
            var eventToCalDate = tempDateFormatter.dateFromString(self.eventTechDate)

            var event:EKEvent = EKEvent(eventStore: eventStore)
            event.title = self.eventTitle
            event.startDate = eventToCalDate
            event.endDate = eventToCalDate
            event.notes = "added from myApp"
            event.calendar = eventStore.defaultCalendarForNewEvents
            eventStore.saveEvent(event, span: EKSpanThisEvent, error: nil)
            println("event added")
        }
    })

这里有什么问题? 另外我想知道如何将事件添加到所有日期,而不仅仅是特定时间。

1 个答案:

答案 0 :(得分:0)

您必须使用

设置event.startDate
[[NSDate date] dateByAddingTimeInterval:date_interval];

e.g:

// your event start date components
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:9];
[comps setMonth:3];
[comps setYear:2015];
[comps setHour:9];
[comps setMinute:0];
[comps setSecond:0];
NSDate * timestamp = [[NSCalendar currentCalendar] dateFromComponents:comps];
NSTimeInterval date_interval = [timestamp timeIntervalSinceDate:[NSDate date]];

EKEvent *event = [EKEvent eventWithEventStore:store];
event.title = @"EVENT TITLE";
event.startDate = [[NSDate date] dateByAddingTimeInterval:date_interval];
event.endDate = [event.startDate dateByAddingTimeInterval:1*60*60];  //set 1 hour meeting
[event setCalendar:[store defaultCalendarForNewEvents]];
NSError *err = nil;
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];