【问题标题】:How to make ios app stop when home button pressed [duplicate]按下主页按钮时如何使ios应用程序停止[重复]
【发布时间】:2017-12-23 00:20:06
【问题描述】:

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

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
    }



}

}

【问题讨论】:

  • 一旦你的应用程序被暂停,计时器就会停止,这会在按下主页按钮后不久发生。您的意思是您希望用户在返回应用程序时必须手动重新启动计时器?
  • 将通知与 .UIApplicationWillEnterForeground 一起使用
  • 多久之后?当计时器运行时,我按下主页,然后在 15 - 30 秒后再次单击应用程序,计时器仍在运行。我希望它在我离开应用程序时停止运行。
  • 没关系,我明白你在说什么。我只是没有给它足够的时间来“暂停”好吧,非常感谢。
  • 您应该使用的@Collin 将辞职活动通知developer.apple.com/documentation/foundation/…

标签: ios swift


【解决方案1】:
override func viewDidLoad() {
    super.viewDidLoad()

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

func appDidEnterBackground() {
    // stop counter
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-10-05
    • 1970-01-01
    • 2011-05-13
    • 2016-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多