我的代码发生了奇怪的事情。
我做了一个由按钮触发的相当简单的Timer函数。
该按钮调用第一个方法,然后该方法使用另一个函数进行计数,然后在时间结束时触发某事。
一切正常。
这是代码。
// This is the declaration of the launch button.
@IBAction func playLater(_ sender: Any) {
if isTimerRunning == false {
runTimer()
}
}
var seconds = 10
var timer = Timer()
var isTimerRunning = false
var resumeTapped = false
//the timer function that sets up the duration and launches the counting.
func runTimer() {
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(self.updateTimer)), userInfo: nil, repeats: true)
isTimerRunning = true
}
//this part is making sure that you go from 10 to 0 and when it's at 0, something happens. In this very case, it plays a song.
@objc func updateTimer() {
if seconds < 1 {
timer.invalidate()
isTimerRunning = false
playNow((Any).self)
} else {
seconds -= 1
timerLabel.text = timeString(time: TimeInterval(seconds))
timerLabel.text = String(seconds)
}
}
问题是我也希望能够从Apple Watch中获得同样的功能。 我做了一个运行良好的WCSession,消息正在传递,没关系。 因此,当用户按下Apple Watch上的按钮时,我正在使用此代码启动相同的功能。代码的那部分是在同一个iOS swift文件中。
@available(iOS 9.0, *)
func session(_ session: WCSession, didReceiveMessage message: [String : Any]) {
// do something
isTimerRunning = false
playLater(Any.self)
}
正如您所看到的,我甚至没有尝试添加一些代码,我只是调用与iOS按钮一起使用的相同功能。 但这一次,它没有用。该方法的第一部分是响应,我看到runTimer()正在工作,但它不会更新updateTimer()。
也许我在这里遗漏了一些东西,但是,有什么区别?为什么如果它来自按下按钮它正在工作,如果直接从“内部”调用它没有发生?
如果您有任何有根据的猜测,甚至是线索,我将不胜感激。 谢谢!