我正在尝试创建一个持续时间为1分钟的计时器,每分钟重复一次,但是从实际时间的下一分钟开始(如下午5:21:00)开始。根据我在这里发现的类似帖子,我正在使用此代码:
@IBAction func switchEnabled(value: Bool) {
if(value){
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Year, .Hour, .Minute, .Second], fromDate: date)
components.minute += 1
components.second = 0
let nextMinuteDate = calendar.dateFromComponents(components)
let doneTimer = NSTimer(fireDate: nextMinuteDate!, interval: 60.0, target: self, selector: Selector("timerDone:"), userInfo: nil, repeats: true)
NSRunLoop.mainRunLoop().addTimer(doneTimer, forMode: NSDefaultRunLoopMode)
// still not working properly
}
else{
print("switch off")
// invalidate timer here
}
}
我的timerDone选择器只打印出“Done!”,但是当我在watchOS 2模拟器上运行并激活开关时,它立即打印完成并且计时器启动一分钟,因此它不会等到被激活。关于这里发生了什么的任何想法?感谢
答案 0 :(得分:0)
class Test: UIViewController{
override func viewDidLoad() {
super.viewDidLoad()
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Second], fromDate: date)
let delayedStart:Double=(Double)(60-components.second)
let dispatchTime: dispatch_time_t = dispatch_time(DISPATCH_TIME_NOW, Int64(delayedStart * Double(NSEC_PER_SEC)))
dispatch_after(dispatchTime, dispatch_get_main_queue(), {
NSTimer.scheduledTimerWithTimeInterval(60.0, target: self, selector: Selector("timerDone:"), userInfo: nil, repeats: true).fire()
})
}
func timerDone(myObj:NSObject){
print("Done")
}
}
如果您遇到任何困难,请告诉我。