3

I want to load events from local phone calendar.

Here is the code:

@IBAction func btnpressed() {
    let eventStore = EKEventStore()

    switch EKEventStore.authorizationStatusForEntityType(EKEntityTypeEvent) {
        case .Authorized:
            println("autorized")
            loadCalendarEvents(eventStore)
        case .Denied:
            println("Access denied")
        case .NotDetermined:
            println("not deter")
            eventStore.requestAccessToEntityType(EKEntityTypeEvent, completion:
                {[weak self] (granted: Bool, error: NSError!) -> Void in
                if granted {
                    println("Access granted")
                    self!.loadCalendarEvents(eventStore)
                } else {
                    println("Access denied")
                }
            })
        default:
            println("Case Default")
    }
}

func getDate(string: String) -> NSDate {
    var dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd"
    dateFormatter.timeZone = NSTimeZone(abbreviation: "GMT+0:00")
    return dateFormatter.dateFromString(string)!
}

func loadCalendarEvents(store: EKEventStore) {
    let calendars = store.calendarsForEntityType(EKEntityTypeEvent) as! [EKCalendar]

    let startDate = getDate("2015-08-26")
    let endDate = getDate("2015-08-29")

    let fetchCalendarEvents: NSPredicate = store.predicateForEventsWithStartDate(startDate, endDate: endDate, calendars: calendars)
    if let eventList: [EKEvent] = store.eventsMatchingPredicate(fetchCalendarEvents) as? [EKEvent] {
        for i in 0..<eventList.count {
            var time = "\(eventList[i].startDate) - \(eventList[i].endDate)"
            println("\(eventList[i].title) - \(eventList[i].location) - \(time)")
        }
    } else {
        println("no events")
    }
}

When I have loaded the events their startDate is a bit incorrect. Example: I add an event at "2015-08-26 00:00:00" but in the debuger it shows as "2015-08-25 21:00:00 +0000". I think that this is because of wrong timeZone. But I don't know where to set it. The below code doesn't work for me:

for i in 0..<eventList.count {
    eventList[i].timeZone = NSTimeZone(abbreviation: "GMT+0:00")
    var time = "\(eventList[i].startDate) - \(eventList[i].endDate)"
    println("\(eventList[i].title) - \(eventList[i].location) - \(time)")
}

Can someone help me with my issue? Thanks.

mkz
  • 2,302
  • 2
  • 30
  • 43

0 Answers0