Pausing timer when app is in background state Swift

后端 未结 5 903
攒了一身酷
攒了一身酷 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:27

    Accepted answer by @Suresh in Swift 3

    Set an observer listening to when the application did enter background in your ViewController's viewDidLoad() method.

     NotificationCenter.default.addObserver(self, selector: #selector(myObserverMethod), name:NSNotification.Name.UIApplicationDidEnterBackground, object: nil)
    

    Add the below function to receive the notification.

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

提交回复
热议问题