2017-10-16 16 views
0

我看到一些涉及此问题的帖子,其中启动多个计时器可能是问题所在。但是,我看不到自己开始超过一个,也许我只是想念一些东西?我对此很新。现在我试图启动计时器,如果用户的速度超过8 mps,并保持运行,直到他停止足够长的时间以使计时器耗尽。目前,即使满足条件以使其无效,定时器仍保持倒计时。计时器不会使无效无效4

感谢一吨看,这里的帮助始终是超级赞赏

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

    } 

} 

回答

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) 
+0

非常感谢,那就是问题:D – Parakoopa