Search code examples
iosswiftuser-interfacetimeravfoundation

timer not working properly,Swift


I'm trying to make a timer count up the seconds I'm holding on a button.(holding to record a video) and its just not working correctly...sometimes its skipping seconds & sometimes just freezes and then speeding up to catch up ...i really need your help solving this, i need the timer to be as fluid and as constant as it can get, thanks.

//Timer Variables:
    var recordingCounter : Timer!
    var minutes: Int = 0
    var seconds: Int = 0
    var counterString : String = ""

func longTap(_ sender: UIGestureRecognizer){
        if sender.state == .ended {
            print("UIGestureRecognizerStateEnded")

            recordingCounter.invalidate()

            seconds = 0
            minutes = 0

            if self.timerView.alpha == 1.0 {
            UIView.animate(withDuration: 0.2, animations: {

                self.timerView.alpha = 0.0
                self.timerView.isHidden = true
                self.recordingCounter.invalidate()

                self.seconds = 0
                self.minutes = 0

                self.counterString = "00:00"
                self.countingLabel.text = self.counterString
            })
            }

    return

        }else if sender.state == .began {

            timerView.isHidden = false
            UIView.animate(withDuration: 0.2, animations: {

                self.timerView.alpha = 1.0

            })

            print("UIGestureRecognizerStateBegan.")

            recordingCounter = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateCounter), userInfo: nil, repeats: true)
        }
    }

func updateCounter() {

        seconds += 1
        if seconds == 60 {

            minutes += 1
            seconds = 0

        }

        let secondsString = seconds > 9 ? "\(seconds)" : "0\(seconds)"
        let minutesString = minutes > 9 ? "\(minutes)" : "0\(minutes)"

        counterString = "\(minutesString):\(secondsString)"
        countingLabel.text = counterString

    }

btw I'm running a VideoPreviewLayer of my custom AVFoundation Camera in the same time.. might cause the problems?


Solution

  • The Timer works in this same DispatchQueue as user interaction (for example scrolling in the UITableView, tap in the UIGestureRecognizer or holding on a UIbutton). So when the user does anything, then the Timer will freeze for a moment.

    You can solve this problem by using, for example, AsyncTimer.