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

标签 swift xcode swift2 ios9 xcode7

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

相关文章:

swift - 在类型 'meow' 上使用实例成员 'Cat' 您是否打算改为使用类型 'Cat' 的值?

swift - vapor 中的异步执行。如何控制in的循环

ios - Swift/iOS - 当设备恢复在线时将离线核心数据与服务器同步

ios - 类型 'MTLBuffer' 的值没有成员 'didModifyRange'

ios - xcode uitableviewcell 选项不包含标识符

ios - 如何让 UIGestureRecognizer 与手动添加的 subview 一起工作

Swift SWRevealController 子菜单

ios - 使用 firebase 获取 UITableview 中的父键

ios - "No matching provisioning profiles"XCode 7.3提交应用到App Store时

ios - Swift 2.2 Xcode 7.3 touch 在下面标记的特定区域不工作