我的问题是我在下面链接的相同问题,但我想在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)