应用程序处于后台状态Swift时暂停计时器 [英] Pausing timer when app is in background state Swift

查看:663
本文介绍了应用程序处于后台状态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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆