Programatically add a reminder to the Reminders ap

2019-04-08 11:11发布

问题:

I'm creating a simple note application and I want to implement Reminders. The user would type a note, tap a button and it would set up a reminder in the Reminders app using the text. Is this possible, and if so, how do I do it? I have seen Apple's documentation on EventKit and EKReminders but it has been no help at all.

回答1:

From the "Calendars and Reminders Programming Guide"? Specifically "Reading and Writing Reminders"

You can create reminders using the reminderWithEventStore: class method. The title and calendar properties are required. The calendar for a reminder is the list with which it is grouped.

Before you create a reminder, ask for permission:

In the .h:

@interface RemindMeViewController : UIViewController
{
    EKEventStore *store;
}

and the .m, when you are going to need access to Reminders:

store = [[EKEventStore alloc] init];
[store requestAccessToEntityType:EKEntityTypeReminder
                      completion:^(BOOL granted, NSError *error) {
                          // Handle not being granted permission
                      }];

To actually add the reminder. This happens asynchronously, so if you try to add a reminder immediately after this, it will fail (crashes the app in my experience).

- (IBAction)addReminder:(id)sender
{
    EKReminder *reminder = [EKReminder reminderWithEventStore:store];
    [reminder setTitle:@"Buy Bread"];
    EKCalendar *defaultReminderList = [store defaultCalendarForNewReminders];

    [reminder setCalendar:defaultReminderList];

    NSError *error = nil;
    BOOL success = [store saveReminder:reminder
                                     commit:YES
                                      error:&error];
    if (!success) {
        NSLog(@"Error saving reminder: %@", [error localizedDescription]);
    }
}