我的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") }
它是打印暂停计时器和关闭应用程序,但当我再次打开时,我看到它从未暂停.我该怎么做?
解决方法
你必须设置一个观察者在应用程序进入后台时监听.在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. }
快乐的编码!!!