【问题标题】:I need to set a notification on a specific day every week.. but I don`t care the day of the month我需要在每周的特定日期设置通知.. 但我不在乎一个月中的哪一天
【发布时间】:2016-08-04 21:39:22
【问题描述】:

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

【问题讨论】:

  • 你的问题是如何让下周日在特定时间设置firedate?
  • mmm 我想在每周的特定日期触发通知,例如:我想在每周一上午 8 点触发通知。我可以用日期的组件来做到这一点,但它只能在今天工作,如果明年有人打开我的应用程序,那么开火日期将是过去
  • 你不明白。获取下一个星期日或星期一的日期,使用日历方法 dateBySettingHour 将所需时间设置为该日期,并使用 weekofyear 重复间隔将其用作触发日期
  • 我做到了,谢谢:)

标签: swift xcode swift2 ios9 xcode7


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-02-07
    • 1970-01-01
    • 2023-03-08
    • 2011-09-26
    • 2019-05-14
    • 1970-01-01
    • 2023-03-28
    • 1970-01-01
    相关资源
    最近更新 更多