How to add an event in the device calendar using swift?

前端 未结 6 1666
孤城傲影
孤城傲影 2020-12-07 17:27

I would be interested in knowing how to add a calendar event in the device, but using swift. I know there are some examples made in Objective-C, but at the moment nothing in

6条回答
  •  抹茶落季
    2020-12-07 18:01

    This was really slow on iOS 11.2 Xcode 9.2, so I modified Luca Davanzo's answer to use queues (works a lot faster):

    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?)
                    }
                })
            }
        }
    

提交回复
热议问题