简体   繁体   中英

Timer will not Invalidate swift 4

I see a couple posts referring to this issue where starting multiple timers might be the problem. However, I do not see myself starting more than one, maybe I am just missing something? I am very new at this. Right now I am trying to start the timer if the user is going faster than 8 mps, and keep it running until he has stopped long enough for the timer to run out. Currently the timer keeps counting down even after the conditions are met to invalidate it.

Thanks a ton for looking, the help here is always super appreciated

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

    }

}

The normal timer function is not getting invalidated even if it is made nil but the below function helped me to solve the purpose. Hope this helps

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

Your problem lies in this part of your code.

Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(timeoutPeriod)), userInfo: nil, repeats: true)

You're creating a Timer but not setting it into the Timer variable you created var timer = Timer()

To fix this you just have to set your Timer variable correctly.

self.timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: (#selector(timeoutPeriod)), userInfo: nil, repeats: true)

Why in my case: First at DidLoad() ran slowly and stopped at increasInt = 9 . Second time triggered by code to make it automatically: reset increasInt = -1 - it ran faster and continues after 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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM