如果fireDate日>如何触发UILocalNotification一个月的最后一天?

时间:2017-01-31 21:35:20

标签: swift3 uilocalnotification repeat

专家,任何帮助将不胜感激。

我在1月30日下午2:00设置了UILocalNotification,并且每月重复一次(localNotification.repeatInterval = NSCalendar.Unit.month)。它在3月30日下午2点触发(所有这一切都很有效)。

但是在2月份,由于当月没有第30天,本地通知不会触发。

如果fireDate大于该月的最后一天,我是否有办法在该月的最后一天触发通知?

修改 以下是基于@MirekE建议的部分解决方案:

func application(_ application: UIApplication, didReceive notification: UILocalNotification) {

    print("comparing fireDate to nextMonthLastDayDate..")
    //get the fire date of the notification received
    let notificationFireDate = notification.fireDate

    //get the last day of the next month
    let now = Date()
    let calendar = Calendar.current
    guard let days = calendar.range(of: .day, in: .month, for: now) else { preconditionFailure("Range of days can't be calculated") }
    let lastDay = days.upperBound - 1
    var lastDayComponents = calendar.dateComponents([.day, .month, .year], from: now)
    lastDayComponents.day = lastDay
    guard let lastDayDate = calendar.date(from: lastDayComponents)  else { preconditionFailure("Date can't be calculated from components") }
    let nextMonthLastDayDate = calendar.date(byAdding: .month, value: 1, to: lastDayDate)

    //if the firedate is greater than the last day fo the next month...
    if notificationFireDate! > nextMonthLastDayDate! {
        //then set the firedate to the last day of the next month
        notification.fireDate = nextMonthLastDayDate
        print("did set fireDate = nextMonthLastDayDate : \(notification.fireDate)")
    } else {
        print("fireDate < nextMonthLastDayDate.  fireDate not changed : \(notification.fireDate)")
    }   
}

现在,当收到最初设定为1月30日(并且每月重复一次)的通知时,它的新fireDate将更改为2月28日。

但是,它将在3月28日之后(而不是3月30日)开火。关于如何确保这一点的任何想法都会回来?

1 个答案:

答案 0 :(得分:0)

根据您的目的,您可以考虑:

将当前日期表示为组件,然后将.day替换为最后一天的值并转换回Date和/或使用Calendar.date(from: DateComponents...)

let now = Date()
let calendar = Calendar.current
guard let days = calendar.range(of: .day, in: .month, for: now) else { preconditionFailure("Range of days can't be calculated") }
let lastDay = days.upperBound - 1

var lastDayComponents = calendar.dateComponents([.day, .month, .year], from: now)
lastDayComponents.day = lastDay

guard let lastDayDate = calendar.date(from: lastDayComponents)  else { preconditionFailure("Date can't be calculated from components") }

let nextMonthLastDayDate = calendar.date(byAdding: .month, value: 1, to: lastDayDate)
相关问题