使用具有递归规则iOS的dueDate设置提醒

时间:2014-07-11 14:20:10

标签: ios date

问题:由于我有重复规则,如何正确设置提醒截止日期?

以下是提醒对象的样子:

EKReminder <0x1700cf490> {title = Dickens's CANINE GOLD WELLNESS doses[1.00]; **dueDate = (null)**; **completionDate = (null)**; priority = 0; calendarItemIdentifier = D1D99FEA-2BFA-4DB1-9D86-7FB26246B50A; alarms = (
    "EKAlarm <0x1780a9420> {triggerInterval = -79200.000000}"
)}

我得到的错误是:

Reminder Error=[A repeating reminder must have a due date.]

您可以在代码中看到我正在使用 NSDateComponents 作为解决方案,因为 startDateComponents 我刚刚设置了月/日/年和本地时区提醒将产生一整天的提醒,在这种情况下是好的。完成后,我可能会在重复部分内移动日期组件和截止日期的设置。

这是我的代码:

-(void)setReminders:(NSString *)reminderText
            andDate:(NSString *)reminderdate
         andPetName:(NSString*)petName
            andDose:(NSNumber *)dose {

    EKEventStore *store = [[EKEventStore alloc] init];

    NSDate * reminderNewDate = [self getDateFromString:reminderdate];
    petName = [ConfigOps readProperty:kConfigOpsPetKey];

    NSString *reminderTitle = [NSString stringWithFormat:@"%@'s %@", petName, reminderText];
    NSUInteger doseCount = 0;

    if ([dose integerValue] != 0 || dose != nil) {
        doseCount = [dose integerValue];
    }
    else{
        doseCount = 0;//NOTE: looks like purchases will have doses not reminders so set to 0 for now.
    }

    [store requestAccessToEntityType:EKEntityTypeReminder completion:^(BOOL granted, NSError *error) {
        // access code here
        EKReminder *new_reminder = [EKReminder reminderWithEventStore:store];
        new_reminder.title = reminderTitle;

        new_reminder.calendar = store.defaultCalendarForNewEvents;

        //get the date components
        NSDateComponents *comp = [[NSDateComponents alloc]init];
        NSCalendar *gregorian = [[NSCalendar alloc]
                                 initWithCalendarIdentifier:NSGregorianCalendar];
        NSDateComponents *weekdayComponents =
        [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit |
                               NSWeekdayCalendarUnit) fromDate:reminderNewDate];
        NSInteger day = [weekdayComponents day];
        NSInteger month = [weekdayComponents month];
        //NSInteger weekday = [weekdayComponents weekday];//future reference
        NSInteger year = [weekdayComponents yearForWeekOfYear];
        //Month is dose+month = end of reccurence
        month = month + doseCount;
        [comp setYear:year];
        [comp setMonth:month];
        [comp setDay:day];
        NSDate *date = [gregorian dateFromComponents:comp];

        NSTimeZone *myNSTimeZone = gregorian.timeZone;
        NSDateComponents *start = new_reminder.startDateComponents;
        start.timeZone = myNSTimeZone;

        start.month = [weekdayComponents month];
        start.day = [weekdayComponents day];
        start.year =  [weekdayComponents yearForWeekOfYear];

        new_reminder.startDateComponents = start;
        new_reminder.dueDateComponents = start;
        new_reminder.completed = NO;

        //Create alarm 22 hours before
        double alarmAmountInSeconds = 60.0*60.0*22.0;
        EKAlarm *alarm = [EKAlarm alarmWithRelativeOffset:(-1.0*alarmAmountInSeconds)];

        [new_reminder addAlarm:alarm];
        //new_reminder.alarms = [NSArray arrayWithObject:alarm];

        //create nice text for note.
        //Hey there! petName needs remindertext from your friendly clinic, clinicName!
        new_reminder.notes = reminderText;

        if (doseCount != 0) {

            EKRecurrenceRule *recurranceRule = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency:EKRecurrenceFrequencyMonthly
                                                                                            interval:1
                                                                                                 end:[EKRecurrenceEnd recurrenceEndWithOccurrenceCount:doseCount]
                                                ];
            new_reminder.calendar = [store defaultCalendarForNewReminders];
            [new_reminder addRecurrenceRule:recurranceRule];
        }

        NSError *er;
        //EKEventEditViewController
        BOOL success = [store saveReminder:new_reminder commit:YES error:&er];

        if (success) {
            // Handle here
             NSString *alertMessage = [NSString stringWithFormat:@"Reminder Created for\n%@", reminderTitle];
             NSString *alertTitle = @"Please check your Reminders";
            UIAlertView *alertR = [[UIAlertView alloc]initWithTitle: alertTitle
                                                            message: alertMessage
                                                           delegate: self
                                                  cancelButtonTitle:nil
                                                  otherButtonTitles:@"OK",nil];
             [alertR show];

        }
        else{
            //log error
            NSLog(@" Reminder Error=[%@]", [er localizedDescription]);
            //log to error table in database &inform Flurry?
        }
    }];
}

如果没有重复集,则该方法有效,因为它不需要开始日期/截止日期。

2 个答案:

答案 0 :(得分:3)

对于那些寻找Swift版本的人:

func editReminder(r: EKReminder) -> Bool {
    if(r.recurrenceRules.count > 0 && r.dueDateComponents == nil) {
        let startDate = NSDate()
        let dueDate: NSDate = NSDate(timeIntervalSinceNow: 31536000) // 1 year from now
        let gregorian = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
        let unitFlags = NSCalendarUnit(UInt.max)
        r.dueDateComponents = gregorian?.components(unitFlags, fromDate: dueDate)
    }
    var error: NSError?
    return eventStore.saveReminder(r, commit: true, error: &error)
}

答案 1 :(得分:2)

在确定一些日期后(我发现它返回为零),我发现在添加剂量时我必须设置并结束复发规则。

以下是摆脱错误的代码(苹果非常有趣 - 感谢Apple!)。

if (doseCount != 0) {

            EKRecurrenceRule *recurranceRule = [[EKRecurrenceRule alloc] initRecurrenceWithFrequency:EKRecurrenceFrequencyMonthly
                                                                                            interval:1
                                                                                                 end:[EKRecurrenceEnd recurrenceEndWithOccurrenceCount:doseCount]
                                                ];
            new_reminder.calendar = [store defaultCalendarForNewReminders];

            //FIX for : recuurence end - Reminder Error = [A repeating reminder must have a due date.]
            EKRecurrenceEnd *endRec = [EKRecurrenceEnd recurrenceEndWithEndDate:date];
            EKRecurrenceRule *recur = [[EKRecurrenceRule alloc]initRecurrenceWithFrequency:EKRecurrenceFrequencyDaily interval:   1 end:endRec];

            unsigned unitFlags= NSYearCalendarUnit|NSMonthCalendarUnit | NSDayCalendarUnit | NSHourCalendarUnit |NSMinuteCalendarUnit|NSSecondCalendarUnit|NSTimeZoneCalendarUnit;

            NSDateComponents *dailyComponents=[gregorian components:unitFlags fromDate:date];
            [new_reminder setDueDateComponents:dailyComponents];
            [new_reminder addRecurrenceRule:recur];

            //add it.
            [new_reminder addRecurrenceRule:recurranceRule];

        }

希望这可以帮助有人度过难关。