iOS通知触发器:每两周和/或每季度

时间:2017-01-03 10:15:53

标签: ios swift notifications calendar

我无法为这个确切的场景找到任何Apple文档,而且我已经尝试了各种方法来做到这一点,而且我一直空着。

我想安排重复通知(iOS 10+所以UNCalendarNotificationTrigger或同等的。) 这些是本地通知 推送通知。

我的目标:

安排重复的通知:

  • 一次两周(例如,每第二周二)
  • 每季度一次(例如,每3个月第1次)

我目前的做法:

这些触发器运行良好,并且易于实现(在Swift Playground中运行代码)。

// Every day at 12pm
var daily = DateComponents()
daily.hour = 12
let dailyTrigger = UNCalendarNotificationTrigger(dateMatching: daily, repeats: true)
dailyTrigger.nextTriggerDate() // "Jan 4, 2017, 12:00 PM"

// Every Tuesday at 12pm
var weekly = DateComponents()
weekly.hour = 12
weekly.weekday = 3
let weeklyTrigger = UNCalendarNotificationTrigger(dateMatching: weekly, repeats: true)
weeklyTrigger.nextTriggerDate() // "Jan 10, 2017, 12:00 PM"

// The 1st of every month at 12pm
var monthly = DateComponents()
monthly.hour = 12
monthly.day = 1
let monthlyTrigger = UNCalendarNotificationTrigger(dateMatching: monthly, repeats: true)
monthlyTrigger.nextTriggerDate() // "Feb 1, 2017, 12:00 PM"

// Every 1st of February at 12pm
var yearly = DateComponents()
yearly.hour = 12
yearly.day = 1
yearly.month = 2
let yearlyTrigger = UNCalendarNotificationTrigger(dateMatching: yearly, repeats: true)
yearlyTrigger.nextTriggerDate() // "Feb 1, 2017, 12:00 PM"

可是...

我似乎无法使fortnightlyquarterly触发器正常运行。

// Every second Tuesday at 12pm
// ... There is no "date.fortnight", is this possible?

// The 1st of every quarter at 12pm
var quarterly = DateComponents()
quarterly.hour = 12
quarterly.day = 4
// Values: 1, 2, 3 or 4 all produce the same "nextTriggerDate" - why?
quarterly.quarter = 4 
let quarterlyTrigger = UNCalendarNotificationTrigger(dateMatching: quarterly, repeats: true)
quarterlyTrigger.nextTriggerDate()

所以,要明确的是,我的问题是:

  1. 是否有可能获得每两周重复一次的通知?
  2. 我们如何每季度获得一次触发器?
  3. 由于DateComponents()具有quarter单位,我认为可以quarterly触发。然而,对于两周一次的提醒,我甚至不确定这是否可能......

    任何见解都将受到赞赏!

1 个答案:

答案 0 :(得分:4)

我没有看到任何触发两周通知的直接选项。从我的结局中提出。

1) 是否有可能获得每两周重复一次的通知?

我提出两个选择:

  1. 我们可以使用UNTimeIntervalNotificationTrigger重复通知,时间间隔为两周吗?以下示例

    let timeInterValFor2Weeks = 1190507.790425003
    
    let intervalTrigger = UNTimeIntervalNotificationTrigger(timeInterval: timeInterValFor2Weeks, repeats: true)//"Jan 3, 2017, 5:24 PM"
    
    intervalTrigger.nextTriggerDate() //"Jan 17, 2017, 12:05 PM"
    
  2. 安排两个UNCalendarNotificationTrigger触发器,该触发器应触发一个月的第一天和第三天。例如,它应该在一个月的第一个星期日和第三个星期日发出通知。

    var fortnightPart1 = DateComponents()
    fortnightPart1.weekday = 1 //(Day..here Sunday)
    fortnightPart1.weekdayOrdinal = 2 //= n == (nth Day in the month...here 2nd Sunday in every month month)
    fortnightPart1.hour = 12
    
    let fortnightTrigger = UNCalendarNotificationTrigger(dateMatching: fortnightPart1, repeats: true)
    fortnightPart1.nextTriggerDate()
    
  3. 2) 我们如何每季度获得一次触发器?

    如果没有可用的直接选项,那么我建议采用与上述相同的解决方案。