Pausing timer when app is in background state Swift

后端 未结 5 912
攒了一身酷
攒了一身酷 2021-01-02 05:57

My ViewController.swift

func startTimer() {
    timer = NSTimer().scheduleTimerWithTimerInvterval(1.0,target: self,selctor: Selector(\"couting\"),userinfo: n         


        
5条回答
  •  遥遥无期
    2021-01-02 06:33

    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.
    }
    

    Happy Coding !!!

提交回复
热议问题