简体   繁体   English

在Swift中从日历中删除所有事件

[英]Remove all the events from a calendar in Swift

有没有可以从Swift中的日历中删除所有事件的命令?

Considering you are saving the events in with startDate , endDate , description and a title 考虑到您正在使用startDateendDatedescriptiontitle保存事件

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: EKSpanThisEvent, error: nil)

Then all you need is to do is delete the event as this: 然后,您所需要做的就是删除事件,如下所示:

  var startDate=NSDate().dateByAddingTimeInterval(-60*60*24)
        var endDate=NSDate().dateByAddingTimeInterval(60*60*24*3)
        var predicate2 = eventStore.predicateForEventsWithStartDate(startDate, endDate: endDate, calendars: nil)

        println("startDate:\(startDate) endDate:\(endDate)")
        var eV = eventStore.eventsMatchingPredicate(predicate2) as [EKEvent]!

        if eV != nil {
            for i in eV {
                println("Title  \(i.title)" )
                println("stareDate: \(i.startDate)" )
                println("endDate: \(i.endDate)" )
              do{
                (try eventStore.removeEvent(i, span: EKSpan.ThisEvent, commit: true))
                }
                catch let error {
                }

            }
        }
    }

Swift 3 compatible : 与Swift 3兼容

func removeAllEventsMatchingPredicate() {
    let startDate = NSDate().addingTimeInterval(60*60*24*(-2))
    let endDate = NSDate().addingTimeInterval(60*60*24*7)

    let predicate2 = eventStore.predicateForEvents(withStart: startDate as Date, end: endDate as Date, calendars: nil)

    print("startDate:\(startDate) endDate:\(endDate)")
    let eV = eventStore.events(matching: predicate2) as [EKEvent]!

    if eV != nil {
        for i in eV! {

            do{
                (try eventStore.remove(i, span: EKSpan.thisEvent, commit: true))
            }
            catch let error {
                print("Error removing events: ", error)
            }

        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM