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

时间:2014-12-29 10:36:10

标签: ios swift nstimer appdelegate

我的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")
}

正在打印暂停计时器和关闭应用但是当我再次打开时,我看到它从未暂停。我该如何正确地做到这一点?

5 个答案:

答案 0 :(得分:24)

你必须设置一个观察者在应用程序进入后台时监听。在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.
}

快乐编码!!!

答案 1 :(得分:2)

@Suresh在Swift 3中接受的回答

设置一个观察者,在应用程序确实在ViewController的viewDidLoad()方法中输入 background 时。

 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.

}

答案 2 :(得分:1)

Swift 5的更新答案:

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

@objc func myObserverMethod(){
    print("Write Your Code Here")
}

答案 3 :(得分:0)

您正在创建一个新对象并在其上调用pauseTimer()

viewController().pauseTimer()   // This line causes issue viewController(), creates a new instance

您应该将该实例传递给AppDelegate并在现有对象上调用pauseTimer()或在视图控制器类中监听UIApplicationDidEnterBackgroundNotification通知,并从那里暂停计时器,而不是创建新对象。

答案 4 :(得分:0)

更新的Swift 4答案:

override func viewDidLoad() {
    super.viewDidLoad()
    NotificationCenter.default.addObserver(self, selector: #selector(myObserverMethod), name:NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
}

@objc func myObserverMethod() {
    // Call your action method here, when the application did enter background.
}