这里使用一个日历事件demo来讲述EventKit的使用。下面这个demo就是对日历事件进行创建和删除。
执行任何事件设备操作的基本工作流程是首先获得事件存储(EventStore)。然后查看是否有权限操作日历。一旦你有权限,你可以创建、或者阅读和删除事件。
- 创建EventStore:
相当于上下文,如果你用一个事件创建一个事件对象存储,你不能在其他地方使用它与另一个事件存储在应用程序中.
- 给出权限:
在创建的EventStore中调用authorizationStatusForEntityType()方法来访问权限,通过entityType访问Entity实体,如果用户没有给我们的应用程序提高权限,就给出是否要访问。那么如何实现访问呢?这里是通过entityType和一个函数,如果用户否认我们的应用程序,该函数不会执行。假设我们获得许可,我们可以执行操作事件存储。
- 创建事件(addEvent)
进行创建Event
- 删除事件(removeEvent)
进行删除Event
下面让代码君出来玩玩了:
import UIKit
import EventKit
class ViewController: UIViewController {
var savedEventId : String = ""
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
// 创建EKEventStore对象
func createEvent(eventStore: EKEventStore, title: String, startDate: NSDate, endDate: NSDate) {
let event = EKEvent(eventStore: eventStore)
event.title = title
event.startDate = startDate
event.endDate = endDate
event.calendar = eventStore.defaultCalendarForNewEvents
do {
try eventStore.saveEvent(event, span: .ThisEvent)
savedEventId = event.eventIdentifier
} catch {
print("有坏银!")
}
}
// 删除EKEventStore
func deleteEvent(eventStore: EKEventStore, eventIdentifier: String) {
let eventToRemove = eventStore.eventWithIdentifier(eventIdentifier)
if (eventToRemove != nil) {
do {
try eventStore.removeEvent(eventToRemove!, span: .ThisEvent)
} catch {
print("Bad things happened")
}
}
}
// 创建事件按钮
@IBAction func addEvent(sender: UIButton) {
let eventStore = EKEventStore()
let startDate = NSDate()
let endDate = startDate.dateByAddingTimeInterval(60 * 60) //一个小时
//判断是否有权限
if (EKEventStore.authorizationStatusForEntityType(.Event) != EKAuthorizationStatus.Authorized) {
eventStore.requestAccessToEntityType(.Event, completion: {
granted, error in
self.createEvent(eventStore, title: "BJEvent", startDate: startDate, endDate: endDate)
})
} else {
createEvent(eventStore, title: "BJEvent", startDate: startDate, endDate: endDate)
}
}
//删除事件按钮
@IBAction func removeEvent(sender: UIButton) {
let eventStore = EKEventStore()
if (EKEventStore.authorizationStatusForEntityType(.Event) != EKAuthorizationStatus.Authorized) {
eventStore.requestAccessToEntityType(.Event, completion: { (granted, error) -> Void in
self.deleteEvent(eventStore, eventIdentifier: self.savedEventId)
})
} else {
deleteEvent(eventStore, eventIdentifier: savedEventId)
}
}
}
代码实在是简单透了,解释就不一步一步的了!