如果有人感到困惑并且认为这与我昨天的问题重复,那就不是了。在那里,我问每天如何调用一个函数,我在这里询问如何在每天的特定时间调用通知。
我正在寻找一种方法,每天早上7点重复本地通知。我目前有这个代码设置来获取日,月,年等。
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: date)
let hour = components.hour
let minutes = components.minute
let month = components.month
let year = components.year
let day = components.day
如何在时间早上7点之前每天拨打通知?
答案 0 :(得分:5)
首先像你一样创建日历对象:
var calendar = NSCalendar()
var calendarComponents = NSDateComponents()
calendarComponents.setHour(7)
calendarComponents.setSeconds(0)
calendarcomponents.setMinutes(0)
calendar.setTimeZone(NSTimeZone.defaultTimeZone)
var dateToFire = calendar.dateFromComponents(calendarComponents)
现在我们可以每天安排通知。
localNotification.fireDate = dateToFire
localNotification.setTimeZone(NSTimeZone.defaultTimeZone)
localNotification.setRepeatInterval(kcfCalendarUnitDay)
语法可能不完美,我是从Obj-C翻译的,但你应该得到一般的想法。
答案 1 :(得分:-3)
var now = NSDate()
var calendar = NSCalendar.currentCalendar()
var components = calendar.components(.CalendarUnitHour | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: now)
var d = NSCalendar.currentCalendar().dateFromComponents(components)
if components.hour > 6 {
d = NSDate(timeInterval: 60*60*24, sinceDate: d!)
}
var n = UILocalNotification()
n.fireDate = d
n.repeatInterval = NSCalendarUnit.CalendarUnitDay
n.alertBody = "This is dayly notification"
UIApplication.sharedApplication().scheduleLocalNotification(n)