使用Swift每周重复本地通知

时间:2016-06-16 17:00:07

标签: ios swift notifications uilocalnotification localnotification

我有一个使用本地通知的应用程序,总共有64个通知,这是本地通知的限制。我需要每周重复一次通知。我知道要设置你使用的重复间隔:

alarm.repeatInterval = NSCalendarUnit

我尝试过使用.WeekOfYear和.WeekOfMonth。他们每年或每月重复通知吗?我不知道每周的日历单位。我可以用哪一个每周重复一次?

编辑:

这是我用来设置通知的代码。

let notifyAlarm = UILocalNotification()
let component = NSDateComponents()
component.hour = NSUserDefaults.standardUserDefaults().integerForKey("Hour1")
component.minute = NSUserDefaults.standardUserDefaults().integerForKey("Minute1")
component.weekday = 1

notifyAlarm.fireDate = calendar.dateFromComponents(component)
notifyAlarm.timeZone = NSTimeZone.defaultTimeZone()
notifyAlarm.alertBody = NSUserDefaults.standardUserDefaults().stringForKey("Message1")
notifyAlarm.repeatInterval = NSCalendarUnit.WeekdayOrdinal
notifyAlarm.soundName = NSUserDefaults.standardUserDefaults().stringForKey("Sound1")
app.scheduleLocalNotification(notifyAlarm)

我一次设置了64个这样的通知。但是有不同的约会。

1 个答案:

答案 0 :(得分:4)

如果您希望在一周后第一次触发通知,则需要更改开火日期。 我使用TimeIntervalSinceNow,这是以秒为单位,因此1周将是604000秒。 您可以使用_来分隔数字以便易读。

alarm.fireDate = NSDate(timeIntervalSinceNow: 604_000)

也许有点笨拙,但我认为这对于那些类型的通知来说最简单。我这样做是为了让它变得更容易。

struct NotificationFireDate {
    static let nextDay: NSTimeInterval = 85_000
    static let nextWeek: NSTimeInterval = 604_000
}

而不是像这样使用

alarm.fireDate = NSDate(timeIntervalSinceNow: NotificationFireDate.nextWeek)

重复间隔应为weekOfYear

alarm.repeatInterval = NSCalendarUnit.WeekOfYear

第一个重复通知应在第一个(fireDate)通知触发后1周触发。

如需完整列表,请查看此内容(感谢madmik3)

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSCalendar_Class/#//apple_ref/c/tdef/NSCalendarUnit

相关问题