Parakoopa
Parakoopa

Reputation: 525

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

    }

}

Upvotes: 3

Views: 6955

Answers (3)

Jaspreet Singh
Jaspreet Singh

Reputation: 51

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

Upvotes: 4

Van TRAN
Van TRAN

Reputation: 21

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)

Upvotes: 2

Zonily Jame
Zonily Jame

Reputation: 5359

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)

Upvotes: 1

Related Questions