当应用程序处于后台状态Swift时暂停计时器
我的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
func applicateWillResignActive(application: UIApplication) { viewController().pauseTimer() println("closing app") }
它正在打印暂停计时器和closures应用程序,但是当我再次打开我看到它永远不会暂停。 我如何正确地做到这一点?
你必须设置一个观察者来监听应用程序何时进入后台。 在ViewController的viewDidLoad()方法中添加下面的代码。
NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("myObserverMethod:"), name:UIApplicationDidEnterBackgroundNotification, object: nil)
添加下面的函数来接收通知。
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 3中被@Suresh接受的答案
设置一个观察者监听应用程序何时在你的ViewController的viewDidLoad()方法中input背景 。
NotificationCenter.default.addObserver(self, selector: #selector(myObserverMethod), name:NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
添加下面的函数来接收通知。
func myObserverMethod(notification : NSNotification) { print("Observer method called") //You may call your action method here, when the application did enter background. //ie., self.pauseTimer() in your case. }
你正在创build一个新的对象,并调用pauseTimer()
:
viewController().pauseTimer() // This line causes issue viewController(), creates a new instance
而不是创build新的对象,或者你应该将该实例传递给AppDelegate并在现有对象上调用pauseTimer(),或者在视图控制器类中侦听UIApplicationDidEnterBackgroundNotification
通知,然后从中暂停计时器。