当app处于后台状态Swift时暂停计时器

use*_*432 9 nstimer ios appdelegate 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")
}
Run Code Online (Sandbox Code Playgroud)

这是appDelegate.swift

func applicateWillResignActive(application: UIApplication) {
    viewController().pauseTimer()
    println("closing app")
}
Run Code Online (Sandbox Code Playgroud)

它是打印暂停计时器和关闭应用程序,但当我再次打开时,我看到它从未暂停.我该怎么做?

Sur*_*raj 25

你必须设置一个观察者在应用程序进入后台时监听.在ViewController的viewDidLoad()方法中添加以下行.

NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("myObserverMethod:"), name:UIApplicationDidEnterBackgroundNotification, object: nil)
Run Code Online (Sandbox Code Playgroud)

添加以下功能以接收通知.

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.
}
Run Code Online (Sandbox Code Playgroud)

快乐的编码!!!


Yun*_*aya 5

Swift 5 的更新答案:

NotificationCenter.default.addObserver
              (self,
               selector: #selector(myObserverMethod),
               name:UIApplication.didEnterBackgroundNotification, object: nil)

@objc func myObserverMethod() {
    print("Write Your Code Here")
}
Run Code Online (Sandbox Code Playgroud)