I have a page on my app that runs a counter when the button is pressed. It stops running when I go to another page or when the app is completely terminated via double tapping home and swiping it away. That's fine with me and exactly what i want it to do. I would also like the counter to stop when i just press the home button even if the app is running still, I want the counter to stop. Ill post my counter below.
class Miner: UIViewController {
//Start
@IBOutlet weak var startMining: UIButton!
//Coin Label
@IBOutlet weak var coinLabel: UILabel!
//Counter
var count:Int {
get {
return UserDefaults.standard.integer(forKey: "count")
}
set {
UserDefaults.standard.set(newValue, forKey: "count")
coinLabel.text = "Coins: 0. \(newValue)"
}
}
var counting:Bool = false
var timer:Timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
}
@objc func counter() -> Void {
count += 1
coinLabel.text = "Coins: 0." + String(count)
walletLabel.text = "Wallet: 0." + String(count)
}
@IBAction func startMining(_ sender: Any) {
if counting {
// Stop Counting
startMining.setTitle("Start", for: .normal)
timer.invalidate()
counting = false
} else if !counting {
// Start Counting
startMining.setTitle("Stop", for: .normal)
// Start timer
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector (counter), userInfo: nil, repeats: true)
counting = true
}
}
}