0

I created a simple stopwatch app while in an iOS course. After I finished, I realized that it doesn't do an important thing, it does not run in background.

How can this be done? I've searched a lot on this topic but however, I couldn't find a proper answer.

Any idea is appreciated. The below code is the one integrated in the app at the moment.

var timer: Timer!
var minutes = 0
var seconds = 0
var fractions = 0
var lapArray: [String]? = []// to track the laps
var addLap = false
var counterString = ""
var isStarted = false


//MARK: - Methods
override func viewDidLoad() {
    super.viewDidLoad()
    makeStatusBarWhite()
    configureInterface()

    timeLabel.text  = "00:00.00"


}


func configureInterface() {
    startButton.layer.cornerRadius = startButton.frame.size.height/2
    lapButton.layer.cornerRadius = startButton.frame.size.height/2
}


@objc func timeDidIncrease() {

    fractions += 1
    if fractions == 100 {
        seconds += 1
        fractions = 0
    }
    if seconds == 60 {
        minutes += 1
        seconds = 0
    }

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


    counterString = "\(minutesString):\(secondsString).\(fractionsString)"
    timeLabel.text = counterString

}


func configureAndStartTimer() {
    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(timeDidIncrease) , userInfo: nil, repeats: true)

    RunLoop.current.add(timer, forMode: RunLoop.Mode.common) //timer will not be affected by UI interaction
}


//MARK: - Actions
@IBAction func didTapLap(_ sender: Any) {

    if isStarted {
        lapArray?.insert(timeLabel.text!, at:0)


    }else {
        timeLabel.text = "00:00.00"
        fractions = 0
        minutes = 0
        seconds = 0
        timer.invalidate()
        lapArray?.removeAll()
        resetStartButton()
        lapButton.setTitle("Lap", for: .normal)
        lapButton.isUserInteractionEnabled = false
        lapButton.alpha = 0.3

    }
    lapsTableView.reloadData()
}
  • in your app delegate monitor when the app resigns and reloads and when it does recalculate the stop watch times. You can set internal notifications on the watch timer as well. – Alex Bailey Nov 25 '18 at 16:33
  • You should never use a timer to measure time. What you need is to store (in UserDefaults) the start date when the user start the timer and use a timer only to display the remaining/elapsed time calculating the time interval between the start date and now. If your app comes back from the background you just need to check if start date it is not nil and update the elapsed or remaining time since the start date stored in user defaults. – Leo Dabus Nov 25 '18 at 22:29

0 Answers0