我的问题与我在下面链接的问题相同,但我想在 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,然后它返回当前时间,我不知道如何设置我想要的小时。
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 重复间隔将其用作 firedate。
关于swift - 我需要在每周的特定日期设置通知..但我不在乎这个月的哪一天,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38777832/