Search code examples
iosswifteventkit

How to add correct time of event in EventKit (swift 4)?


I am coming to a minor issue where when I implemented a logic to add an event every other friday. But, for some reason the time it is wrong. It always shows 12:00AM by default. Is there a way to set the time of the event to 6:30PM? I need some help to solve this minor issue. I checked the EventKit documentation. But got stuck. thanks for the help.

import UIKit
import EventKit

class EducationPillarViewController: UIViewController {



     override func viewDidLoad() {
        super.viewDidLoad()

    }


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



    @IBAction func MyStudyButtonWasTapped(_ sender: Any) {

        let alertController = UIAlertController(title: "My Study", message:"Every other Fridays at 6:30PM ", preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "Ok", style: .cancel, handler: nil)
        let addtocalendarAction = UIAlertAction(title: "Add to Calendar", style: .default, handler: someHandler)


        alertController.addAction(defaultAction)
        alertController.addAction(addtocalendarAction)
        present(alertController, animated: true, completion: nil)
  }

    func someHandler(alert: UIAlertAction!) {

    let friday = EKRecurrenceDayOfWeek(.friday)


        let dateFormatter = DateFormatter()
        dateFormatter.dateStyle = .short

      let startWeek = Date().startOfWeek
        let endWeek = Date().endOfWeek



   EKRecurrenceRule(recurrenceWith: .weekly, interval: 2, daysOfTheWeek: [friday], daysOfTheMonth: nil, monthsOfTheYear: nil, weeksOfTheYear: nil, daysOfTheYear: nil, setPositions: nil, end: nil)


    addEventToCalendar(title: "My Study", description: "Every Other Fridays", startDate: startWeek!, endDate: endWeek!)


    let alertControlller = UIAlertController(title: "My Study", message: "My Study event has been added to your calendar", preferredStyle: .alert)
        let defaultAction = UIAlertAction(title: "ok", style: .cancel, handler: nil)
        alertControlller.addAction(defaultAction)
        self.present(alertControlller, animated: true, completion: nil)


    }




}

extension Date {
    var startOfWeek: Date? {
        let gregorian = Calendar(identifier: .gregorian)
        guard let friday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
        return gregorian.date(byAdding: .day, value: 5, to: friday)
    }

    var endOfWeek: Date? {
        let gregorian = Calendar(identifier: .gregorian)
        guard let friday = gregorian.date(from: gregorian.dateComponents([.yearForWeekOfYear, .weekOfYear], from: self)) else { return nil }
        return gregorian.date(byAdding: .day, value: 5, to: friday)
    }
}

Solution

  • You could add another function to the extension Date block

    public func setTime(hour: Int, min: Int, sec: Int) -> Date? {
            let x: Set<Calendar.Component> = [.year, .month, .day, .hour, .minute, .second]
            let cal = Calendar.current
            var components = cal.dateComponents(x, from: self)
    
    
            components.hour = hour
            components.minute = min
            components.second = sec
    
            return cal.date(from: components)
        }
    

    Then once you've done that chagne your line of code that declares the startWeek variable let startWeek = Date().startOfWeek to var startWeek = Date().startOfWeek.Then below that line put startWeek = startWeek?.setTime(hour: 12, min: 30, sec: 00).

    Finally change the endWeek variable

    var endWeek = Date().endOfWeek endWeek = endweek?.setTime(hour: 13, min: 30, sec: 00)