我需要在每周的特定日期设置通知..但我不在乎这个月的哪一天

I need to set a notification on a specific day every week.. but I don`t care the day of the month

我的问题与我在下面链接的问题相同,但我想在 swift 2 中而不是在 objective-c

中这样做

Fire a notification at a specific day and time every week

问题是我使用的日期默认是 1 月 1 日,因为我没有指定月、日和年,但是如果我指定了它们就没用了,因为我的应用明年或下个月将无法运行

我想要的很简单..设置每周日通知(例如)

但指定年份或月份不切实际,因为它应该在任何星期日或任何星期六工作

请帮助我:(我已经尝试了很多

let calendar = NSCalendar.currentCalendar()
let components = NSDateComponents()


components.hour = 2
components.minute = 54
components.weekday = 6

var newDate = calendar.dateFromComponents(components)
let notification = UILocalNotification()
notification.fireDate = newDate
notification.alertBody = "Swipe to unlock"
notification.alertAction = "You've got a class soon!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["CustomField1": "w00t"]
notification.timeZone = NSTimeZone.localTimeZone()
notification.repeatInterval = NSCalendarUnit.WeekOfYear


UIApplication.sharedApplication().scheduleLocalNotification(notification)

更新:

我知道它只能在星期一工作,但我可以稍后修复。 这里的问题是我将小时和分钟设置为 0,然后 returns 当前时间,我不知道如何设置我想要的小时。

var pickerDate = NSDate()
print(pickerDate)

var dateComponents: NSDateComponents? = nil
var calendar = NSCalendar.currentCalendar()


dateComponents = calendar.components(NSCalendarUnit.NSWeekdayCalendarUnit, fromDate: pickerDate)
var firstMondayOrdinal = 9 - dateComponents!.weekday
dateComponents =  NSDateComponents()
dateComponents!.day = firstMondayOrdinal
dateComponents?.hour = 0
dateComponents?.minute = 0
var firstMondayDate = calendar.dateByAddingComponents(dateComponents!, toDate: pickerDate, options: NSCalendarOptions(rawValue: 0))

dateComponents = NSDateComponents()
dateComponents?.weekdayOrdinal = 1



let notification = UILocalNotification()
notification.fireDate = firstMondayDate
notification.alertBody = "Swipe to unlock"
notification.alertAction = "You've got a class soon!"
notification.soundName = UILocalNotificationDefaultSoundName
notification.userInfo = ["CustomField1": "w00t"]
notification.timeZone = NSTimeZone.localTimeZone()
notification.repeatInterval = NSCalendarUnit.WeekOfYear


UIApplication.sharedApplication().scheduleLocalNotification(notification)

获取下一个星期日或星期一的日期 (SO answer),使用日历方法 dateBySettingHour 将所需时间设置为该日期,并使用 weekofyear 重复间隔将其用作日期。