我看到一些帖子提到这个问题,其中启动多个计时器可能是问题所在。但是,我不认为自己开始不止一个,也许我只是缺少一些东西?我很陌生。现在我正在尝试启动计时器,如果用户速度超过8 mps,并保持运行直到他停止足够长的时间让计时器用完。目前,即使满足条件,计时器仍会倒计时,以使其无效。
非常感谢您的帮助,这里的帮助总是非常受欢迎
import UIKit
class ViewController: UIViewController, {
//Setup timer
var timer = Timer()
var seconds = 5
var timerRunning = false
//Timer countdown
@objc func timeoutPeriod() {
seconds -= 1
}
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if userLocation.speed > 8 && timerRunning == false {
//flip running to True and start timer
timerRunning = true
seconds = 10
Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(timeoutPeriod)), userInfo: nil, repeats: true)
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
let placemark: CLPlacemark = placemarks![0]
if let city = placemark.locality {
self.startingLocation = city
print("Starting Location: " + city)
}
})
} else if userLocation.speed > 8 && timerRunning == true {
seconds = 10
} else if seconds == 0 {
//end timer (hopefully)
self.timer.invalidate()
geoCoder.reverseGeocodeLocation(location, completionHandler: { (placemarks, error) -> Void in
let placemark: CLPlacemark = placemarks![0]
if let city = placemark.locality {
self.currentDateString = self.dateFormatter.string(from: self.date)
self.endingLocation = city
print("Ending Location: " + city)
self.timerRunning = false
self.seconds = 10
}
})
}
}
}
答案 0 :(得分:3)
即使将其设置为nil,正常的计时器功能也不会失效,但是以下功能帮助我解决了这个问题。希望这会有所帮助
self.myTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (timerValue) in
if self.myTimer != nil {
self.updateTimerLabel() // call the selector function here
}
})
答案 1 :(得分:1)
您的问题在于代码的这一部分。
Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(timeoutPeriod)), userInfo: nil, repeats: true)
您正在创建计时器,但未将其设置为您创建的Timer
变量var timer = Timer()
要解决此问题,您只需正确设置Timer
变量即可。
self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(timeoutPeriod)), userInfo: nil, repeats: true)
答案 2 :(得分:1)
为什么在我的情况下:
首先在DidLoad()
处跑步,然后在increasInt = 9
处停下来。
第二次由代码触发以使其自动运行:reset increasInt = -1 -
运行速度更快
并在increasInt > 11
func aniDrag(ani: Double){
dragTimer = Timer.scheduledTimer(timeInterval: ani, target: self, selector: #selector(updatedrag), userInfo: nil, repeats: true)
}
@objc func updatedrag() { // dauIndex
increasInt = increasInt + 1
if (increasInt > -1 ) && ( increasInt < 10 ) {
aniImage.image = UIImage(named: "ani" + allLessonArray[realnIndex] + String(increasInt))!
print(allLessonArray[realnIndex] + String(increasInt) )
}
if increasInt == 10 {
if dragTimer != nil {
print("Timer Stop !!!!!")
dragTimer.invalidate()}
}
if increasInt > 11 { print(increasInt)}
}
//test aniDrag(ani: 0.5)