let chosenDate = "01.11.2015" // example date chosen with your DateTimePicker
var dateTimer = NSTimer.scheduledTimerWithTimeInterval(60.0 * 60, target: self, selector: Selector("checkDate"), userInfo: nil, repeats: true)
func checkDate() {
let date = NSDate()
println(date)
let formatter = NSDateFormatter()
formatter.dateFormat = "dd.MM.yyyy"
let formattedDate = formatter.stringFromDate(date)
if formattedDate == chosenDate {
helloWorldTimer.invalidate() // disable previous timer
dateTimer.invalidate() // must also stop this timer as attempting to invalidate the other once already stopped would cause a crash
}
}
2 回答
您需要使用像
NSTimer
之类的东西来安排像这样的重复任务(时间以秒为单位):然后你还需要设置另一个类似于上面的计时器来检查日期(在这个例子中它每小时都这样做,但你可以通过改变间隔来增加/减少准确度) . 一旦日期与您匹配,则使前一个计时器无效以停止它重复:
注:确保您的日期都采用相同的格式进行比较
n.b.2 . 这是使用Swift 1.2编写的
使用
NSTimer
'scheduledTimerWithTimeInterval:target: selector:userInfo:nil repeats:
根据用户选择的值触发和停止通知 .Running NSTimer in Background