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