Collin Collin - 2 months ago 24
iOS Question

How to make ios app stop when home button pressed

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 {

@IBOutlet weak var startMining: UIButton!

//Coin Label
@IBOutlet weak var coinLabel: UILabel!

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



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


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



Answer Source
override func viewDidLoad() {

    NotificationCenter.default.addObserver(self, selector: #selector(appDidEnterBackground), name: .UIApplicationDidEnterBackground, object: nil)

func appDidEnterBackground() {
    // stop counter
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download