Created
August 18, 2020 16:22
-
-
Save yuraist/126f9deaf99c7d8c021da8bd8abebd7c to your computer and use it in GitHub Desktop.
Synchronise tasks from the Reminders app within your iOS app using EventKit.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import EventKit | |
class RemindersSync { | |
let eventStore = EKEventStore() | |
var remindersCalendar: EKCalendar? = nil | |
var reminders: [EKReminder] = [] | |
/// Requests access to the Reminders app | |
func requestRemindersAccess(completion: @escaping (Bool) -> Void) { | |
eventStore.requestAccess(to: .reminder) { (granted, error) in | |
if let error = error { | |
print("EKEventStore request access completed with error: \(error.localizedDescription)") | |
completion(granted) | |
return | |
} | |
completion(granted) | |
} | |
} | |
/// Creates a new calendar for the Reminders app if there is no calendar yet. | |
/// Either it fetches an existing calendar, and set it as the `remindersCalendar` property. | |
/// The custom calendar is shown as regular list in the Reminders app. | |
func createRemindersCalendar() { | |
let calendar = EKCalendar(for: .reminder, eventStore: eventStore) | |
calendar.source = eventStore.defaultCalendarForNewReminders()?.source // Use the default store for new reminders | |
calendar.title = "My App List" // the title will be used as a list title in the Reminders | |
calendar.cgColor = UIColor.systemIndigo.cgColor // the color will be used as a list color in the Reminders | |
do { | |
try eventStore.saveCalendar(calendar, commit: true) | |
} catch { | |
print("Calendar creation failed with error: \(error.localizedDescription)") | |
return | |
} | |
remindersCalendar = calendar | |
} | |
func fetchReminders() { | |
guard let remindersCalendar = remindersCalendar else { return } | |
let predicate = eventStore.predicateForReminders(in: [remindersCalendar]) // Use nil insted of [remindersCalendar] to fetch reminders from the default list | |
eventStore.fetchReminders(matching: predicate) { results in | |
if let results = results { | |
self.reminders = results | |
} | |
} | |
} | |
func createReminder(_ title: String) { | |
let reminder = EKReminder(eventStore: eventStore) | |
reminder.title = title | |
reminder.calendar = remindersCalendar | |
// You can create a completed task | |
// reminder.isCompleted = false | |
// You can set a task deadline | |
// reminder.dueDateComponents = DateComponents() | |
do { | |
try eventStore.save(reminder, commit: true) | |
} catch { | |
print("Saving reminder failed with error: \(error.localizedDescription)") | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment