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