如何在按下主页按钮时停止ios应用程序

时间:2017-12-23 00:20:06

标签: ios swift

我的应用程序上有一个页面,按下按钮时会运行一个计数器。当我转到另一个页面或当应用程序完全终止时,它会停止运行,通过双击回家并将其擦掉。这对我来说很好,也正是我想要的。即使应用程序仍在运行,我也希望计数器在我按下主页按钮时停止,我希望计数器停止。生病了我的柜台下面。

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
    }



}

}

1 个答案:

答案 0 :(得分:1)

override func viewDidLoad() {
    super.viewDidLoad()

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

func appDidEnterBackground() {
    // stop counter
}