Friday, January 6, 2017

Swift 3 Adding all-day event to Device Calendar

If you have your contact’s Birthday date added while creating contact, Your iOS device Calendar shows you the Birthday reminder as all-day event as shown below.




In the same way, From our iOS app also we can add all-day events to the device calendar. In this post let me show you how can we do that using Swift.

  1. We need to import EventKit framework.
  2. We need to add privacy description for the in info.plist file.
  3. In my case it is Privacy - Calendars Usage Description (testing all-day event). This will be displayed to the user when OS asks for Calendar permissions to the user.


That’s it. Time for Swift code do add event to device Calendar

  
        
        let startDate = Calendar.current.startOfDay(for: Date())
        let store = EKEventStore()
        store.requestAccess(to: .event) {(granted, error) in
            if !granted {
                return
            }
            let event = EKEvent(eventStore: store)
            event.isAllDay = true
            event.title = "Business Meeting"
            event.notes = "Discussion on stocks."
            event.location = "New York City"
            event.startDate = startDate
            event.endDate = startDate
            event.calendar = store.defaultCalendarForNewEvents
            do {
                try store.save(event, span: .thisEvent, commit: true)
            } catch {
            }
        }
    }


If you see the above code,

We need to take the EventStore object
Request for access, which shows the below access request popup to the user.



If the request is granted, all we need to do is take EKEvent object and pass
  1. isAllDay - As we are adding all-day events, This value is true
  2. title - Title for event
  3. notes - Description of Event
  4. location - Where the event is going to happen
  5. startDate - Start date of the event (As it is all-day, both start and end dates are same)
  6. endDate - End date of the event 

That’s it. Save event using the store object we have created.

Now close the app and goto device calendar. You can see all-day event we have added as shown below.



Hope this post is useful. Feel free to comment in case of any queries.
       

  

1 comment:

  1. Nice Blog.
    Swift protocols and extensions that you mentioned in the blog is very useful for all the users who want to learn about swift. I was looking for a swift app development company and got your blog. Thanks for sharing such a great blog.
    Synsoft Global

    ReplyDelete