How to Add an Event in the Device Calendar Using Swift

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

Note: If your app is crashing with This app has crashed because it attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain an NSCalendarsUsageDescription key with a string value explaining to the user how the app uses this data., you'll need to add NSCalendarsUsageDescription to your info.plist. Can follow the example here.

Swift 5.0 Version

import Foundation
import EventKit

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

Reference : https://gist.github.com/mchirico/d072c4e38bda61040f91

Add Event to Calendar in iOS8 with Swift

This works for me in Swift 3.0

Firstly, You need to add "Privacy - Calendars Usage Description" in info.plist.

import EventKit

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

Then, you can easily call this method like the following:

addEventToCalendar(title: "Best friend birthday", description: "Remember you or miss you!", startDate: NSDate(), endDate: NSDate())

Thanks and enjoy coding!!!

Can I open the the add event to calendar screen of the IOS calendar app with pre-filled data from my app?

Yes, You can use EventKitUI framework for that.

Use EKEventEditViewController.

Presented modally, the event edit view controller provides a way for
users to add new events, as well as edit or delete events from their
calendar.

Ref : Apple

For pre-filled values use event property.

// Create event 
var store = EKEventStore()
var event = EKEvent(eventStore: store)
event.title = "Title"
//event.startDate = startDate
//event.endDate = currentEvent?.endDate


let eventViewController: EKEventEditViewController = EKEventEditViewController()
eventViewController.event = event
eventViewController.eventStore = store
eventViewController.editViewDelegate = self

present(eventViewController, animated: true, completion: nil)

Programmatically add custom event in the iPhone Calendar

Based on Apple Documentation, this has changed a bit as of iOS 6.0.

1) You should request access to the user's calendar via "requestAccessToEntityType:completion:" and execute the event handling inside of a block.

2) You need to commit your event now or pass the "commit" param to your save/remove call

Everything else stays the same...

Add the EventKit framework and #import <EventKit/EventKit.h> to your code.

In my example, I have a NSString *savedEventId instance property.

To add an event:

    EKEventStore *store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) { return; }
EKEvent *event = [EKEvent eventWithEventStore:store];
event.title = @"Event Title";
event.startDate = [NSDate date]; //today
event.endDate = [event.startDate dateByAddingTimeInterval:60*60]; //set 1 hour meeting
event.calendar = [store defaultCalendarForNewEvents];
NSError *err = nil;
[store saveEvent:event span:EKSpanThisEvent commit:YES error:&err];
self.savedEventId = event.eventIdentifier; //save the event id if you want to access this later
}];

Remove the event:

    EKEventStore* store = [EKEventStore new];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) { return; }
EKEvent* eventToRemove = [store eventWithIdentifier:self.savedEventId];
if (eventToRemove) {
NSError* error = nil;
[store removeEvent:eventToRemove span:EKSpanThisEvent commit:YES error:&error];
}
}];

This adds events to your default calendar, if you have multiple calendars then you'll have find out which one that is

Swift version

You need to import the EventKit framework

import EventKit

Add event

let store = EKEventStore()
store.requestAccessToEntityType(.Event) {(granted, error) in
if !granted { return }
var event = EKEvent(eventStore: store)
event.title = "Event Title"
event.startDate = NSDate() //today
event.endDate = event.startDate.dateByAddingTimeInterval(60*60) //1 hour long meeting
event.calendar = store.defaultCalendarForNewEvents
do {
try store.saveEvent(event, span: .ThisEvent, commit: true)
self.savedEventId = event.eventIdentifier //save event id to access this particular event later
} catch {
// Display error to user
}
}

Remove event

let store = EKEventStore()
store.requestAccessToEntityType(EKEntityTypeEvent) {(granted, error) in
if !granted { return }
let eventToRemove = store.eventWithIdentifier(self.savedEventId)
if eventToRemove != nil {
do {
try store.removeEvent(eventToRemove, span: .ThisEvent, commit: true)
} catch {
// Display error to user
}
}
}

Save event to user's calendar

You can use Apple's native calendar API. Use EKEventEditViewController in the EventKitUI framework, and the user will be able to specify the calendar when saving the event. In Swift 3:

import UIKit
import EventKit
import EventKitUI

class ViewController: UIViewController {

let store = EKEventStore()

func createEvent() {
// create the event object

let event = EKEvent(eventStore: store)
event.title = "Foo"
event.startDate = ...
event.endDate = ...

// prompt user to add event (to whatever calendar they want)

let controller = EKEventEditViewController()
controller.event = event
controller.eventStore = store
controller.editViewDelegate = self
present(controller, animated: true)
}
}

extension ViewController: EKEventEditViewDelegate {

func eventEditViewController(_ controller: EKEventEditViewController, didCompleteWith action: EKEventEditViewAction) {
controller.dismiss(animated: true)
}
}

In Swift 2.3:

import UIKit
import EventKit
import EventKitUI

class ViewController: UIViewController {

let store = EKEventStore()

func createEvent() {
// create the event object

let event = EKEvent(eventStore: store)
event.title = "Foo"
event.startDate = ...
event.endDate = ...

// prompt user to add event (to whatever calendar they want)

let controller = EKEventEditViewController()
controller.event = event
controller.eventStore = store
controller.editViewDelegate = self
presentViewController(controller, animated: true, completion: nil)
}
}

extension ViewController: EKEventEditViewDelegate {

func eventEditViewController(controller: EKEventEditViewController, didCompleteWithAction action: EKEventEditViewAction) {
controller.dismissViewControllerAnimated(true, completion: nil)
}
}

This assumes that you've supplied a NSCalendarsUsageDescription in your Info.plist, that you've requested access, etc.



Related Topics



Leave a reply



Submit