当应用程序处于后台状态 Swift 时暂停计时器 [英] Pausing timer when app is in background state Swift
本文介绍了当应用程序处于后台状态 Swift 时暂停计时器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我的 ViewController.swift
My ViewController.swift
func startTimer() {
timer = NSTimer().scheduleTimerWithTimerInvterval(1.0,target: self,selctor: Selector("couting"),userinfo: nil, repeats: true)
}
func pauseTimer() {
timer.invalidate()
println("pausing timer")
}
这是 appDelegate.swift
and this is appDelegate.swift
func applicateWillResignActive(application: UIApplication) {
viewController().pauseTimer()
println("closing app")
}
它正在打印暂停计时器和关闭应用,但当我再次打开时,我看到它从未暂停.我该如何正确操作?
It is printing pausing timer and closing app but when I open again I see it never paused. How do I do it correctly?
推荐答案
你必须设置一个观察者在应用程序进入后台时监听.在 ViewController 的 viewDidLoad() 方法中添加以下行.
You have to set an observer listening to when the application did enter background. Add the below line in your ViewController's viewDidLoad() method.
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("myObserverMethod:"), name:UIApplicationDidEnterBackgroundNotification, object: nil)
添加下面的函数来接收通知.
Add the below function to receive the notification.
func myObserverMethod(notification : NSNotification) {
println("Observer method called")
//You may call your action method here, when the application did enter background.
//ie., self.pauseTimer() in your case.
}
快乐编码!!!
这篇关于当应用程序处于后台状态 Swift 时暂停计时器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文