如何检索当天的日历事件?

时间:2017-05-25 07:11:23

标签: ios swift uitableview eventkit

我想在tableView中检索当前日期的数据/事件,我想我需要使用EventKit,但不知道该怎么做。

这是我尝试过的,但似乎不起作用:它只显示部分但不显示事件的标签

class ViewController: UIViewController,UITableViewDelegate{

@IBOutlet weak var taskShow: UITableView!
var titles : [String] = []

override func viewDidLoad() {
    super.viewDidLoad()

    let eventStore = EKEventStore()

    switch EKEventStore.authorizationStatus(for: .event) {
    case .authorized:
        readEvents()
    case .denied:
        print("Access denied")
    case .notDetermined:

        eventStore.requestAccess(to: .event, completion: { (granted: Bool, NSError) -> Void in
            if granted {
                self.readEvents()

            }else{
                print("Access denied")
            }



        })
    default:
        print("Case Default")
    }
    self.taskShow.reloadData()
}

func readEvents() {


    let eventStore = EKEventStore()
    let calendars = eventStore.calendars(for: .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.predicateForEvents(withStart: oneMonthAgo as Date, end: oneMonthAfter as Date, calendars: [calendar])

            var events = eventStore.events(matching: predicate)

            for event in events {

                titles.append(event.title)
  }}}}


func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
    return titles.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell", for: indexPath as IndexPath)


    cell.textLabel!.text = titles[indexPath.row]
    // Configure the cell...

    return cell
}

1 个答案:

答案 0 :(得分:0)

您可以使用EventKit来阅读日历事件.Apple已经记录了EventKit.please的使用,请参阅Apple链接下面的详细信息。 https://developer.apple.com/library/content/documentation/DataManagement/Conceptual/EventKitProgGuide/ReadingAndWritingEvents.html