swift - 定时器不会使swift 4无效

标签 swift timer

我看到一些帖子提到这个问题,其中启动多个计时器可能是问题所在。但是,我不认为自己开始不止一个,也许我只是错过了什么?我对此很陌生。现在,如果用户的速度超过 8 英里/秒,我将尝试启动计时器,并保持它运行,直到他停止足够长的时间以使计时器用完。目前,即使满足使其失效的条件,计时器仍会继续倒计时。

非常感谢您的浏览,非常感谢这里的帮助

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
                }
            })
        }

    }

}

最佳答案

正常的计时器功能即使设为 nil 也不会失效,但下面的功能帮助我解决了这个问题。希望这有帮助

 self.myTimer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true, block: { (timerValue) in
        if self.myTimer != nil {
            self.updateTimerLabel()  // call the selector function here
        }
    })

关于swift - 定时器不会使swift 4无效,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46761922/

相关文章:

ios - Swift 和录音

xcode - 制作尾随像素的最佳方法?

java - 为什么此 Swing Timer 代码会抛出 NullPointerException?

c - 选择性重复 ARQ 中的定时器

xcode - Swift:通过代码更改 Storyboard上元素的位置

swift - 检查对象是否是列表的一部分

java - 如何为同一个 EJB @Timeout 方法创建多个触发器?

ios - 多个定时器 Objective-C

ios - 该请求在 iOS 10.0+ 模拟器上被服务委托(delegate) (SBMainWorkspace) 拒绝,在 iOS 9.3 模拟器上出现 FBSOpenApplicationErrorDomain 错误 1。为什么?

android - 数 45 秒,暂停 20 秒,然后用不同的标题重复