Command line app to show reminders

I'm trying to create a very simple command line app that shows all my reminders in the command line but I'm simply not getting any reminders shown (yes I do have some).

import Foundation
import EventKit

let eventStore: EKEventStore = EKEventStore()
let defaultList: EKCalendar?
var hasAccess: Bool = false
var reminders: [EKReminder]?

eventStore.requestAccess(to: EKEntityType.reminder, completion: {(granted, error) in
      hasAccess = granted ? true : false
    })

print("Has access: \(hasAccess)")

defaultList = eventStore.defaultCalendarForNewReminders()
print("Default List: \(defaultList?.title ?? "NONE")")

let lists = eventStore.calendars(for: .reminder)
print(lists.map {$0.title})

eventStore.fetchReminders(matching: eventStore.predicateForReminders(in: nil)) { (_ rems: [EKReminder]?) -> Void in
  print(rems)
  reminders = rems
  }

print(reminders)

As you can see, this is very simply. I get my hasAccess successfully and my defaultList and my lists but not my reminders.

I think this is because the fetchReminders function takes a completion and so this is something to do with threads or callbacks or something but the requestAccess function also has a completion but that works.

Please help!

I think this is because the fetchReminders(…) function takes a completion and so this is something to do with threads or callbacks or something

Right. What’s happening here is that you fall off the end of the main ‘function’ before the completion handler runs, and that calls exit which terminates your process.

but the requestAccess(…) function also has a completion but that works.

It’s probably just that the latter runs fast enough that the completion happens before your process terminates.

When calling async APIs from a command line tool you have three options:

  • Park the main thread in a run loop.

  • Park the main thread in dispatchMain() [1].

  • Using Swift concurrency with an async main.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

[1] Technically the main thread terminates in this case but I say “park” because it’s easier to understand (-:

Command line app to show reminders
 
 
Q