Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • Easy trick to add an Event in the System Calendar using Swift 3.0

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 745
    Comment on it

    The EventKit framework allows the applications to access the calendar on iOS Devices. However, before accessing the calendar, we are required to import EventKit framework in our controller.

     

    import EventKit

     

    To add events to a calendar, we first require the user permission to access the calendar. Once the permission is granted, we may use the below-mentioned code to add events to a calendar.

     

    // Pass the date for which event has to be added
    func insertEvent(date : NSDate) {  
     //EKEventStore class represents the Calendar database. The application accesses the calendar using     EKEventStore.
    
           let eventStore : EKEventStore = EKEventStore()
           //Ask for permission to access system calendar
           eventStore.requestAccess(to: EKEntityType.event) { (granted,error) in
                if (granted) &&  (error == nil) {
                    print("permission is granted")
                    let event:EKEvent = EKEvent(eventStore: eventStore)
                    event.title = "TYPE YOUR TITLE HERE"
                    event.startDate = date as Date
                    event.endDate = date as Date
                    event.notes = "This is a test of creating event"
                    event.calendar = eventStore.defaultCalendarForNewEvents
                    event.addAlarm(EKAlarm.init(relativeOffset: 60.0))
                    do {
                        try eventStore.save(event, span: .thisEvent)
                    } catch let specError as NSError {
                        print("A specific error occurred: \(specError)")
                    } catch {
                        print("An error occurred")
                    }
                   
                    print("Event saved")
    
                } else {
                  print("need permission to create a event")
                }
            }   
    
    }

     

    Hope it works!

     

    Please share and promote the blog on Social Media channels.

     

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: