无法在iOS 6中保存EKReminder

我试图从我的应用程序保存/检索提醒,但由于某种原因,EKReminder似乎没有被保存.这是我的代码:

EKEventStore * _eventStore = [[EKEventStore alloc] init];
[_eventStore requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError *error) {

    //create a new calendar for reminders.
    EKCalendar *calendar = [EKCalendar calendarForEntityType:EKEntityTypeReminder eventStore:_eventStore];
    EKSource *localSource = nil;
    for (EKSource *source in _eventStore.sources)
        if (source.sourceType == EKSourceTypeLocal)
        {
            localSource = source;
            break;
        }

    calendar.source = localSource;

    self.calendarIdentifier = calendar.calendarIdentifier;
    EKReminder *reminder = [EKReminder reminderWithEventStore:_eventStore];
    reminder.calendar = calendar;
    reminder.title = @"Test Reminder";
    reminder.startDateComponents = [[NSCalendar currentCalendar] components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit fromDate:[NSDate date]];
    reminder.completionDate = [NSDate dateWithTimeIntervalSinceNow:100];

    EKAlarm *alarm = [EKAlarm alarmWithAbsoluteDate:[NSDate dateWithTimeIntervalSinceNow:100]];
    reminder.alarms = @[alarm];      

    NSError *errorOb = nil;
    BOOL saved = [_eventStore saveReminder:reminder commit:YES error:&errorOb];
    if (saved) NSLog(@"Saved Reminder");
    else NSLog(@"Failed to save reminder");

}];

然后,我试图验证提醒实际上已被保存.我通过使用此代码来做到这一点:

NSPredicate *predicate = [_eventStore predicateForRemindersInCalendars:nil];
[_eventStore fetchRemindersMatchingPredicate:predicate completion:^(NSArray *reminders) {
    for (EKReminder *reminder in reminders) {
        NSLog(@"Reminder Title: %@", reminder.title);
    }
}];

我的新提醒永远不会出现!

谁能告诉我我在做错了什么?

最佳答案 您只需要调用-requestAccessToEntityType:completion:如果授权状态是EKAuthorizationStatusNotDetermined.您可以使用[EKEventStore authorizationStatusForEntityType:]检查授权状态.

然后,只有在第一次调用-requestAccessToEntityType:completion时才会调用完成块.在模拟器上它甚至不会被调用一次,因为在模拟器上你的应用程序已经可以访问.

EKEventStore * _eventStore = [[EKEventStore alloc] init];
EKAuthorizationStatus authorizationStatus = [EKEventStore authorizationStatusForEntityType:EKEntityTypeReminder];
if (authorizationStatus == EKAuthorizationStatusNotDetermined) {
    [_eventStore requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError *error) {
        if (granted) {
            [self createNewReminder];
        } else {
            [self showNowAccessAlert];
        }
    }];
} else {
    if (authorizationStatus == EKAuthorizationStatusAuthorized) {
        [self createNewReminder];
    } else {
        [self showNowAccessAlert];
    }
}
点赞