答案 0 :(得分:0)
假设您使用的是swift,您可以像这样创建一个日历
// Create an Event Store instance
let eventStore = EKEventStore();
// Use Event Store to create a new calendar instance
// Configure its title
let newCalendar = EKCalendar(forEntityType: .Event, eventStore: eventStore)
// Probably want to prevent someone from saving a calendar
// if they don't type in a name...
newCalendar.title = "Some Calendar Name"
// Access list of available sources from the Event Store
let sourcesInEventStore = eventStore.sources
// Filter the available sources and select the "Local" source to assign to the new calendar's
// source property
newCalendar.source = sourcesInEventStore.filter{
(source: EKSource) -> Bool in
source.sourceType.rawValue == EKSourceType.Local.rawValue
}.first!
// Save the calendar using the Event Store instance
do
{
try eventStore.saveCalendar(newCalendar, commit: true)
NSUserDefaults.standardUserDefaults().setObject(newCalendar.calendarIdentifier, forKey: "EventTrackerPrimaryCalendar")
}
catch
{
let alert = UIAlertController(title: "Calendar could not save", message: (error as NSError).localizedDescription, preferredStyle: .Alert)
let OKAction = UIAlertAction(title: "OK", style: .Default, handler: nil)
alert.addAction(OKAction)
self.presentViewController(alert, animated: true, completion: nil)
}
}
}
将活动添加到特定日历
eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion: {
(granted, error) in
if (granted) && (error == nil) {
println("granted \(granted)")
println("error \(error)")
var event:EKEvent = EKEvent(eventStore: eventStore)
event.title = "Test Title"
event.startDate = NSDate()
event.endDate = NSDate()
event.notes = "This is a note"
event.calendar = newCalendar
eventStore.saveEvent(event, span: EKSpanThisEvent, error: nil)
println("Saved Event")
}
})
并且可以获取特定日历的事件
func loadEvents() {
// Create a date formatter instance to use for converting a string to a date
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd"
// Create start and end date NSDate instances to build a predicate for which events to select
let startDate = dateFormatter.dateFromString("2016-01-01")
let endDate = dateFormatter.dateFromString("2016-12-31")
if let startDate = startDate, endDate = endDate {
let eventStore = EKEventStore()
// Use an event store instance to create and properly configure an NSPredicate
let eventsPredicate = eventStore.predicateForEventsWithStartDate(startDate, endDate: endDate, calendars: [newCalendar])
// Use the configured NSPredicate to find and return events in the store that match
self.events = eventStore.eventsMatchingPredicate(eventsPredicate).sort(){
(e1: EKEvent, e2: EKEvent) -> Bool in
return e1.startDate.compare(e2.startDate) == NSComparisonResult.OrderedAscending
}
}
}