我很想知道如何在设备中添加日历事件,但使用swift。我知道在Objective-C中有一些例子,但目前没什么好快的。非常感谢。
答案 0 :(得分:49)
Swift 3.0版本
let eventStore : EKEventStore = EKEventStore()
// 'EKEntityTypeReminder' or 'EKEntityTypeEvent'
eventStore.requestAccess(to: .event) { (granted, error) in
if (granted) && (error == nil) {
print("granted \(granted)")
print("error \(error)")
let event:EKEvent = EKEvent(eventStore: eventStore)
event.title = "Test Title"
event.startDate = Date()
event.endDate = Date()
event.notes = "This is a note"
event.calendar = eventStore.defaultCalendarForNewEvents
do {
try eventStore.save(event, span: .thisEvent)
} catch let error as NSError {
print("failed to save event with error : \(error)")
}
print("Saved Event")
}
else{
print("failed to save event with error : \(error) or access not granted")
}
}
参考:https://gist.github.com/mchirico/d072c4e38bda61040f91
答案 1 :(得分:47)
兼容Swift 3.0:
func addEventToCalendar(title: String, description: String?, startDate: Date, endDate: Date, completion: ((_ success: Bool, _ error: NSError?) -> Void)? = nil) {
let eventStore = EKEventStore()
eventStore.requestAccess(to: .event, completion: { (granted, error) in
if (granted) && (error == nil) {
let event = EKEvent(eventStore: eventStore)
event.title = title
event.startDate = startDate
event.endDate = endDate
event.notes = description
event.calendar = eventStore.defaultCalendarForNewEvents
do {
try eventStore.save(event, span: .thisEvent)
} catch let e as NSError {
completion?(false, e)
return
}
completion?(true, nil)
} else {
completion?(false, error as NSError?)
}
})
}
并导入EventKit
因此,您可以轻松地从任何地方调用此方法:
addEventToCalendar(title: "Girlfriend birthday", description: "Remember or die!", startDate: NSDate(), endDate: NSDate())
如果您愿意,可以将此方法放在一个utiliy类中,并将其定义为' static'。
答案 2 :(得分:8)
您需要在info.plist中添加“隐私 - 日历使用说明”。 以下代码适用于最新版本的xcode和swift 3。
import EventKit
class EventHelper
{
let appleEventStore = EKEventStore()
var calendars: [EKCalendar]?
func generateEvent() {
let status = EKEventStore.authorizationStatus(for: EKEntityType.event)
switch (status)
{
case EKAuthorizationStatus.notDetermined:
// This happens on first-run
requestAccessToCalendar()
case EKAuthorizationStatus.authorized:
// User has access
print("User has access to calendar")
self.addAppleEvents()
case EKAuthorizationStatus.restricted, EKAuthorizationStatus.denied:
// We need to help them give us permission
noPermission()
}
}
func noPermission()
{
print("User has to change settings...goto settings to view access")
}
func requestAccessToCalendar() {
appleEventStore.requestAccess(to: .event, completion: { (granted, error) in
if (granted) && (error == nil) {
DispatchQueue.main.async {
print("User has access to calendar")
self.addAppleEvents()
}
} else {
DispatchQueue.main.async{
self.noPermission()
}
}
})
}
func addAppleEvents()
{
let event:EKEvent = EKEvent(eventStore: appleEventStore)
event.title = "Test Event"
event.startDate = NSDate() as Date
event.endDate = NSDate() as Date
event.notes = "This is a note"
event.calendar = appleEventStore.defaultCalendarForNewEvents
do {
try appleEventStore.save(event, span: .thisEvent)
print("events added with dates:")
} catch let e as NSError {
print(e.description)
return
}
print("Saved Event")
}
}
答案 3 :(得分:3)
我能够对此进行调整,并消除上述答案(以及其他一些答案)评论中提到的编译器错误,如下所示:
var eventStore : EKEventStore = EKEventStore()
// 'EKEntityTypeReminder' or 'EKEntityTypeEvent'
eventStore.requestAccessToEntityType(EKEntityType.Event, completion: {
(granted, error) in
if (granted) && (error == nil) {
print("granted \(granted)")
print("error \(error)")
var event:EKEvent = EKEvent(eventStore: eventStore)
event.title = "Test Title"
event.startDate = NSDate()
event.endDate = NSDate()
event.notes = "This is a note"
event.calendar = eventStore.defaultCalendarForNewEvents
eventStore.saveEvent(event, span: EKSpan.ThisEvent, error: nil)
print("Saved Event")
}
})
但是,我仍然在底部收到关于“EKSpan.ThisEvent”的错误:调用中的参数标签不正确(包含':span:error:',expected':span:commit: “)。
我尝试将“error”更改为“commit”,但它给了我一个编译错误,说它预期Bool而不是nil。这似乎是一个与swift语法中的更新有关的问题。
编辑:我最终关注this tutorial,并且能够让它发挥作用。
首先,请求访问日历的权限,并且(如果授予该权限)调用函数来添加事件。
var savedEventId : String = ""
func requestAccessPermission() {
let eventStore = EKEventStore()
let startDate = NSDate()
let endDate = startDate.dateByAddingTimeInterval(60 * 60) // Ends one hour later
if (EKEventStore.authorizationStatusForEntityType(.Event) != EKAuthorizationStatus.Authorized) {
eventStore.requestAccessToEntityType(.Event, completion: {
granted, error in
self.createEvent(eventStore, title: "Test Title", startDate: startDate, endDate: endDate)
})
} else {
createEvent(eventStore, title: "Test Title", startDate: startDate, endDate: endDate)
}
}
在上面的代码段中调用的函数,用于添加事件:
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("Error Saving")
}
}
答案 4 :(得分:2)
这在iOS 11.2 Xcode 9.2上非常慢,所以我修改了Luca Davanzo的使用队列的答案(工作速度更快):
func addEventToCalendar(title: String, description: String?, startDate: Date, endDate: Date, completion: ((_ success: Bool, _ error: NSError?) -> Void)? = nil) {
DispatchQueue.global(qos: .background).async { () -> Void in
let eventStore = EKEventStore()
eventStore.requestAccess(to: .event, completion: { (granted, error) in
if (granted) && (error == nil) {
let event = EKEvent(eventStore: eventStore)
event.title = title
event.startDate = startDate
event.endDate = endDate
event.notes = description
event.calendar = eventStore.defaultCalendarForNewEvents
do {
try eventStore.save(event, span: .thisEvent)
} catch let e as NSError {
completion?(false, e)
return
}
completion?(true, nil)
} else {
completion?(false, error as NSError?)
}
})
}
}
答案 5 :(得分:0)
与位置和警报相同
func addEventToCalendar(title: String, description: String?, startDate: Date, endDate: Date, location: String?, completion: ((_ success: Bool, _ error: NSError?) -> Void)? = nil) {
DispatchQueue.global(qos: .background).async { () -> Void in
let eventStore = EKEventStore()
eventStore.requestAccess(to: .event, completion: { (granted, error) in
if (granted) && (error == nil) {
let alarm = EKAlarm(relativeOffset: -3600.0)
let event = EKEvent(eventStore: eventStore)
event.title = title
event.startDate = startDate
event.endDate = endDate
event.notes = description
event.alarms = [alarm]
event.location = location
event.calendar = eventStore.defaultCalendarForNewEvents
do {
try eventStore.save(event, span: .thisEvent)
} catch let e as NSError {
completion?(false, e)
print ("\(#file) - \(#function) error: \(e.localizedDescription)")
return
}
completion?(true, nil)
} else {
completion?(false, error as NSError?)
print ("\(#file) - \(#function) error: \(error)")
}
})
}
}