Как получить все события из календаря (Swift)
Я немного новичок в Swift, но очень заинтересован. Я хотел бы получить все события, которые я сохранил в Календаре под названием «Работа», и показать их в табличном представлении. Я искал подобные вопросы, но код, показанный там, вроде бы старый и не очень работает. Как я могу это сделать? TableView должен отображать заголовок, дату начала и окончания. Можно ли получить как все названия в массиве строк. То же самое с началом и концом? Было бы здорово получить несколько советов!
Обновление: я объявил переменные вне класса. Теперь я попробовал код, который выглядит следующим образом, благодаря полученному здесь ответу, но я не получаю, чтобы ячейки отображали что-либо ?! И да, я уже создал testEvent в своем рабочем календаре на симуляторе.
override func viewDidAppear(animated: Bool) {
let eventStore = EKEventStore()
switch EKEventStore.authorizationStatusForEntityType(.Event) {
case .Authorized:
readEvents()
case .Denied:
print("Access denied")
case .NotDetermined:
eventStore.requestAccessToEntityType(.Event, completion: { (granted: Bool, NSError) -> Void in
if granted {
self.readEvents()
}else{
print("Access denied")
}
})
default:
print("Case Default")
}
self.tableView.reloadData()
}
func readEvents() {
let eventStore = EKEventStore()
let calendars = eventStore.calendarsForEntityType(.Event)
for calendar in calendars {
if calendar.source.title == "Work" {
let oneMonthAgo = NSDate(timeIntervalSinceNow: -30*24*3600)
let oneMonthAfter = NSDate(timeIntervalSinceNow: +30*24*3600)
let predicate = eventStore.predicateForEventsWithStartDate(oneMonthAgo, endDate: oneMonthAfter, calendars: [calendar])
var events = eventStore.eventsMatchingPredicate(predicate)
for event in events {
titles.append(event.title)
startDates.append(event.startDate)
endDates.append(event.endDate)
}
}
}
}
// MARK: - Table view data source
override func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
// #warning Incomplete implementation, return the number of rows
return titles.count
}
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("cell", forIndexPath: indexPath)
cell.textLabel!.text = titles[indexPath.row]
cell.detailTextLabel!.text = "From: \(startDates[indexPath.row]) Until: \(endDates[indexPath.row])"
// Configure the cell...
return cell
}