Swift - 使用EventKit获取系统日历事件,添加事件

首先要在info.plist中申请权限
字段名:NSCalendarsUsageDescription
屏幕快照 2017-03-15 下午3.00.00.png
import UIKit
//导入头文件
import EventKit
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let eventStore = EKEventStore()
        eventStore.requestAccess(to: .event, completion: {
            granted, error in
            if (granted) && (error == nil) {
                print("granted \(granted)")
                print("error  \(error)")
                
                // 新建一个事件
                let event:EKEvent = EKEvent(eventStore: eventStore)
                event.title = "新增一个测试事件"
                event.startDate = Date()
                event.endDate = Date()
                event.notes = "这个是备注"
                event.calendar = eventStore.defaultCalendarForNewEvents
                
                do{
                    try eventStore.save(event, span: .thisEvent)
                    print("Saved Event")
                }catch{}
                
                // 获取所有的事件(前后90天)
                let startDate = Date().addingTimeInterval(-3600*24*90)
                let endDate = Date().addingTimeInterval(3600*24*90)
                let predicate2 = eventStore.predicateForEvents(withStart: startDate,
                                                               end: endDate, calendars: nil)
                
                print("查询范围 开始:\(startDate) 结束:\(endDate)")
                
                if let eV = eventStore.events(matching: predicate2) as [EKEvent]! {
                    for i in eV {
                        print("标题  \(i.title)" )
                        print("开始时间: \(i.startDate)" )
                        print("结束时间: \(i.endDate)" )
                    }
                }
            }
        })
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}

![Uploading 屏幕快照 2017-03-15 下午2.57.22_552844.png . . .]

你可能感兴趣的:(Swift - 使用EventKit获取系统日历事件,添加事件)