Repeat UILocalNotification on Specific day

后端 未结 5 1493
滥情空心
滥情空心 2021-02-03 14:30

I need to set UILocalNotification, I just need to take hour and minute from DatePicker and need to set specific date ( like : Monday ) and repeat it on every Monday.

5条回答
  •  温柔的废话
    2021-02-03 14:59

    This solution also takes time in account but it's a bit more simplified than Oren's

    -(NSDate *) dateOfSpecificDay:(NSInteger ) day withFireTime:(NSDate *)timeDate/// here day will be 1 or 2.. or 7 and timeDate the current day with the desired time 
    {
        NSInteger desiredWeekday = day;
        NSRange weekDateRange = [[NSCalendar currentCalendar] maximumRangeOfUnit:NSCalendarUnitWeekday];
        NSInteger daysInWeek = weekDateRange.length - weekDateRange.location + 1;
    
        NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:[NSDate date]];
        NSInteger currentWeekday = dateComponents.weekday;
        NSInteger differenceDays = (desiredWeekday - currentWeekday + daysInWeek) % daysInWeek;
        if (differenceDays == 0) {
            //Check if should register for same day or for next week
            if ([timeDate compare:[NSDate date]] == NSOrderedAscending) {
                //Should schedule for next week
                differenceDays = daysInWeek;
            }
        }
    
        NSDateComponents *daysComponents = [[NSDateComponents alloc] init];
        daysComponents.day = differenceDays;
        NSDate *resultDate = [[NSCalendar currentCalendar] dateByAddingComponents:daysComponents toDate:timeDate options:0];
    
        return resultDate;
    }
    

提交回复
热议问题