0

I want to Stop my Timer when the Phone is Locking so how i can do That ? in the code i set the Timer when he get in the Background Mode so away it works but i have no idea how to make that that the time stop when the phone get locked. Have anyone an idea ?

var backgroundTaskIdentifier: UIBackgroundTaskIdentifier?

override func viewDidLoad() {
    super.viewDidLoad()


    backgroundTaskIdentifier = UIApplication.shared().beginBackgroundTask {
        UIApplication.shared().endBackgroundTask(self.backgroundTaskIdentifier!)

    }

    timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: #selector(LoangeController.cosumTime), userInfo: nil, repeats: true)
    startTime = NSDate.timeIntervalSinceReferenceDate()




}


func cosumTime() {

    let currentTime = NSDate.timeIntervalSinceReferenceDate()

    var elapsedTime: TimeInterval = currentTime - startTime

    let hours = UInt8(elapsedTime / 3600.0)

    elapsedTime -= (TimeInterval(hours) * 3600)

    let minutes = UInt8(elapsedTime / 60.0)

    elapsedTime -= (TimeInterval(minutes) * 60)

    let seconds = UInt8(elapsedTime)

    elapsedTime -= TimeInterval(seconds)


    //add the leading zero for minutes, seconds and millseconds and store them as string constants

    let strHours = String(format: "%02d", hours)
    let strMinutes = String(format: "%02d", minutes)
    let strSeconds = String(format: "%02d", seconds)

    let counttime =  "\(strHours): \(strMinutes): \(strSeconds)"

    timeconsum = counttime

    print("\(counttime)")


    if timeconsum == timeout {
        print("Remind TimeOut")
        let UUID = Foundation.UUID().uuidString

        Notification.addNotification(title: "TimeOut Put your Phone away", date: CurrentTime, uuid: UUID)

    }
}

2 Answers2

0

You need to add the applicationWillResignActive handler in your app delegate

func applicationWillResignActive(_ application: UIApplication) {
     //Pause timer
}

This should be called whenever the phone is locked or goes to sleep.

Luke
  • 4,908
  • 1
  • 37
  • 59
0

Luke has the right answer, I'm just going to add more detail. In your app delegate you can add

func applicationWillResignActive(application: UIApplication) {
  // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
}

If you need to resume the timer on active you can use this method in your app delegate

func applicationDidBecomeActive(application: UIApplication) {
     // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
}

For more info on stopping and starting timers, I recommend this link. Best of luck! How can I pause and resume NSTimer.scheduledTimerWithTimeInterval in swift?

Community
  • 1
  • 1
Amloelxer
  • 752
  • 2
  • 8
  • 20
  • So this function are when the user go out from my app but i need a func when the user lock his phone, give it this func ? – Michael Diabolo Jul 13 '16 at 23:50
  • There is currently no specific delegate method that will notify that app when the user has locked the phone. You can only be notified when the app moves to an inactive state. Luckily, when the user locks the phone, the app quickly moves to inactive, virtually doing the same thing you are looking for. – Amloelxer Jul 14 '16 at 17:45
  • Oke, Thanks for your Help – Michael Diabolo Jul 14 '16 at 20:23
  • Anytime! Happy coding – Amloelxer Jul 14 '16 at 20:29