Repeat UILocalNotification on Specific day

后端 未结 5 1492
滥情空心
滥情空心 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:43

    Here is the swift version:

    func calculateTheNExtFriday(inputTime: NSDate) -> NSDate {
        let desiredWeekday = 6 // Friday
    
        let weekDateRange = NSCalendar.currentCalendar().maximumRangeOfUnit(NSCalendarUnit.Weekday)
        let daysInWeek = weekDateRange.length - weekDateRange.location + 1;
    
        let currentWeekday = NSCalendar.currentCalendar().components(NSCalendarUnit.Weekday, fromDate: inputTime).weekday
        let differenceDays = (desiredWeekday - currentWeekday + daysInWeek) % daysInWeek
    
        let dateComponents = NSDateComponents()
        dateComponents.day = differenceDays
    
        let calculatedFridayDate = NSCalendar.currentCalendar().dateByAddingComponents(dateComponents, toDate: inputTime, options: NSCalendarOptions.init(rawValue: 0))
        return calculatedFridayDate!
    }
    

    In this example, I use the desiredWeekday inside the function but you can use it as parameter as well.

    NB: Keep in mind that the day 1 corresponds to Sunday, 2 -> Monday and so on

提交回复
热议问题