我是Swift的新手,但真的很感兴趣。
我想获取我存储在称为“工作”的日历中的所有事件,并在tableView中显示它们。
我一直在寻找这样的问题,但是那里显示的代码似乎有点陈旧,并且没有真正起作用。我怎么做? 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
}
最佳答案
您可以尝试这样的事情
import EventKit
var titles : [String] = []
var startDates : [NSDate] = []
var endDates : [NSDate] = []
let eventStore = EKEventStore()
let calendars = eventStore.calendarsForEntityType(.Event)
for calendar in calendars {
if calendar.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)
}
}
}