Get minutes remaining between dates in Swift - swift

My question is based on a time interval
I'm getting the hour and minutes (NOW) and I want to create a timer for 75 minutes since that moment but I want the timer to continue working even if i close the app even on multitasking
So i was thinking if I save the time as a NSUserDefault value and every time I open the app It reads the stored value and recalculates
This is my actual code
override func viewDidLoad() {
super.viewDidLoad()
var timer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}
func update() {
//here I should update the GUI with the remaining minutes and do a NSUserDefault check if the 75 minutes have already
}
#IBAction func save_time(sender: AnyObject) {
let date = NSDate()
let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
var hour = components.hour
var minutes = components.minute + 75
if (minutes>59){
hour += 1
minutes -= 60
}
defs.setInteger(hour, forKey: "u_hora")
defs.setInteger(minutes, forKey: "u_minutos")
}

You can just store them as TimeInterval using NSUserDefaults and you should create a time interval extension to format your time string as desired:
import UIKit
class ViewController: UIViewController {
#IBOutlet weak var strTimer: UILabel!
var tasksManager = NSTimer()
var endTime:NSTimeInterval = 0
var now: NSTimeInterval {
return NSDate().timeIntervalSinceReferenceDate
}
func updateTime(){
strTimer.text = ( endTime - now ).time
}
override func viewDidLoad() {
super.viewDidLoad()
// NSUserDefaults().removeObjectForKey("endTime")
// loads endTime if it exists otherwise assign 0 value
endTime = NSUserDefaults().valueForKey("endTime") as? NSTimeInterval ?? 0
// restart timer if endTime exists
if endTime > 0 {
tasksManager = NSTimer.scheduledTimerWithTimeInterval(1/15, target: self, selector: "updateTime", userInfo: nil, repeats:true)
} else {
strTimer.text = "0:01:00.00"
}
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
#IBAction func startTimer (sender: AnyObject) {
// sets endTime new timeinterval to a future point in time
// so we need to add n seconds from now
endTime = now + 60.0 // now + n seconds
// saves it using NSUserDefaults
NSUserDefaults().setValue(endTime, forKey: "endTime")
// if the timer doest exists we create one
if !tasksManager.valid {
tasksManager = NSTimer.scheduledTimerWithTimeInterval(1/30, target: self, selector: "updateTime", userInfo: nil, repeats:true)
// if the timer exists we invalidate it
} else {
tasksManager.invalidate()
endTime = 0
strTimer.text = "0:01:00.00"
NSUserDefaults().removeObjectForKey("endTime")
}
}
}
extension NSTimeInterval {
var time: String {
return String(format: "%d:%02d:%02d.%02d", Int(self/3600), Int(self/60%60), Int(self%60), Int(self*100%100))
}
}

You can save the current date and time in NSUserDefaults like this.
NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: "dateKey")
You can calculate the number of minutes elapsed between saved time and current time in this way.
if let savedDate = NSUserDefaults.standardUserDefaults().objectForKey("dateKey") as? NSDate
{
let currentDate = NSDate()
let distanceBetweenDates = currentDate.timeIntervalSinceDate(savedDate)
let secondsInAnMinute = 60.0;
let minutesElapsed = distanceBetweenDates / secondsInAnMinute;
println(minutesElapsed)
println(distanceBetweenDates)
}

Related

Label with Timer not Stopping

I am creating a lap stopwatch, and I am having trouble stopping the timer when the "STOP" button is clicked. I am able to get the text to reset to 0, but the timer keeps running and if I hit start again the timer is running as if I never hit stop.
Timer code:
func goTimer()
{
if timer == nil {
timer = Timer.scheduledTimer(timeInterval : 0.1,
target : self,
selector :#selector(timerAction(_:)),
userInfo: nil, repeats: true);
}
}
func stopTimer()
{
if timer != nil {
timer!.invalidate()
timer = nil
}
}
func updateTimer() {
let intervalTotal = -Int(startDate.timeIntervalSinceNow)
let hours = intervalTotal / 3600
let minutes = intervalTotal / 60 % 60
let seconds = intervalTotal % 60
if startButton.currentTitle == "STOP" {
totalTime.text = String(format: "%02i:%02i:%02i", hours, minutes, seconds)
lapTime.text = String(format: "%02i:%02i:%02i", hours, minutes, seconds)
}
}
#objc func timerAction (_ timer : Timer) {
print("timerAction(_:)")
self.updateTimer()
}
#IBAction func startTimer(_ sender: Any) {
if startButton.currentTitle == "STOP" {
startButton.backgroundColor = UIColor.systemGreen
startButton.setTitle("START", for : .normal)
stopTimer()
lapTime.text = "00:00:00"
}
else if startButton.currentTitle == "START" {
startButton.backgroundColor = UIColor.systemRed
startButton.setTitle("STOP", for : .normal)
goTimer()
lapButton.isEnabled = true
lapButton.backgroundColor = UIColor.systemBlue
}
}
let intervalTotal = -Int(startDate.timeIntervalSinceNow)
I don't see you resetting that startDate in your stopTimer() function.
you have a variable
var startDate: Date = Date()
somewhere on top of your code. If its not a variable (if its let) change it to variable. You want to set this value when you start your timer. so
func goTimer() {
// Add this to set the date to when your function starts
startDate = Date()
....
}
That's because when you're setting the value in your label here
func updateTimer() {
let intervalTotal = -Int(startDate.timeIntervalSinceNow)
....
}
you're setting the value from startDate until now

Cannot assign to value: 'setText' is a method

Im using Xcode Version 11.0 (11A420a) and Swift to make an iPhone and Apple Watch app I have some code that has made a simple timer label and start and stop buttons and Id like to also have that on the Apple Watch.
In the Xcode viewcontroller.swift file I have this code and it works great.
var startTime = TimeInterval()
var startofTime = Date()
var timer:Timer = Timer()
var endTime: Date!
#IBOutlet weak var timerLabel: UILabel!
#IBOutlet weak var Start: UIButton!
#IBOutlet weak var Stop: UIButton!
#IBAction func startAct(_ sender: Any) {
alarmTime = Date()
startofTime = Date()
Start.isHidden = true
Stop.isHidden = false
if (!timer.isValid) {
let aSelector : Selector = #selector(ViewController.updateTime)
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = Date.timeIntervalSinceReferenceDate
}
}
#IBAction func stopAction(_ sender: Any) {
progressView.progress = 0.0
progress.completedUnitCount = 1024
Start.isHidden = false
Stop.isHidden = true
endTime = Date()
timer.invalidate()
}
#objc func updateTime() {
let currentTime = Date.timeIntervalSinceReferenceDate
//Find the difference between current time and start time.
var elapsedTime: TimeInterval = currentTime - startTime
// print(elapsedTime)
// print(Int(elapsedTime))
//calculate the hours in elapsed time.
let hours = UInt8(elapsedTime / 3600.0)
elapsedTime -= (TimeInterval(hours) * 3600)
//calculate the minutes in elapsed time.
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (TimeInterval(minutes) * 60)
//calculate the seconds in elapsed time.
let seconds = UInt8(elapsedTime)
elapsedTime -= TimeInterval(seconds)
//find out the fraction of milliseconds to be displayed.
let fraction = UInt8(elapsedTime * 100)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)
//concatenate minuets, seconds and milliseconds as assign it to the UILabel
timerLabel.text = "\(hours):\(strMinutes):\(strSeconds).\(strFraction)"
}
When I tried to copy it to the watch InterfaceController.swift I got most of it done by just coping and pasting but I get a error about the label.
!Cannot assign to value: 'setText' is a method
Can anyone help me with the label for the watch. Something like this -
timerLabel.setText = "\(hours):\(strMinutes):\(strSeconds).\(strFraction)"
if I just put
timerLabel.setText((strFraction))
It works to display the milliseconds but id like to combine them all please.
If I do this
timerLabel.setText((strSeconds)(strFraction))
I get this error
!Cannot call value of non-function type 'String'
This is the full watch code so far, just need the last line
//
// InterfaceController.swift
// WatchKit Extension
//
// Created by Kurt on 3/10/19.
// Copyright © 2019 Kurt. All rights reserved.
//
import WatchKit
import Foundation
class InterfaceController: WKInterfaceController {
override func awake(withContext context: Any?) {
super.awake(withContext: context)
// Configure interface objects here.
}
override func willActivate() {
// This method is called when watch view controller is about to be visible to user
super.willActivate()
}
override func didDeactivate() {
// This method is called when watch view controller is no longer visible
super.didDeactivate()
}
var startTime = TimeInterval()
var startofTime = Date()
var timer:Timer = Timer()
var endTime: Date!
#IBOutlet weak var timerLabel: WKInterfaceLabel!
#IBAction func Start() {
startofTime = Date()
if (!timer.isValid) {
let aSelector : Selector = #selector(InterfaceController.updateTime)
timer = Timer.scheduledTimer(timeInterval: 0.01, target: self, selector: aSelector, userInfo: nil, repeats: true)
startTime = Date.timeIntervalSinceReferenceDate
}
}
#objc func updateTime() {
let currentTime = Date.timeIntervalSinceReferenceDate
//Find the difference between current time and start time.
var elapsedTime: TimeInterval = currentTime - startTime
// print(elapsedTime)
// print(Int(elapsedTime))
//calculate the hours in elapsed time.
let hours = UInt8(elapsedTime / 3600.0)
elapsedTime -= (TimeInterval(hours) * 3600)
//calculate the minutes in elapsed time.
let minutes = UInt8(elapsedTime / 60.0)
elapsedTime -= (TimeInterval(minutes) * 60)
//calculate the seconds in elapsed time.
let seconds = UInt8(elapsedTime)
elapsedTime -= TimeInterval(seconds)
//find out the fraction of milliseconds to be displayed.
let fraction = UInt8(elapsedTime * 100)
//add the leading zero for minutes, seconds and millseconds and store them as string constants
let strMinutes = String(format: "%02d", minutes)
let strSeconds = String(format: "%02d", seconds)
let strFraction = String(format: "%02d", fraction)
//concatenate minuets, seconds and milliseconds as assign it to the UILabel
timerLabel.setText(\(hours):\(strMinutes):\(strSeconds).\(strFraction)) !error
}
}
You can do it as,
timerLabel.setText("\(hours):\(strMinutes):\(strSeconds).\(strFraction)")
The setText method isn't available for the UILabel class in Swift.
Assuming you've created a setText extension method to the UILabel class,
you can do it this way:
timerLabel.setText("\(hours):\(strMinutes):\(strSeconds).\(strFraction)")
The setText method isn't available for the UILabel class in Swift. You can use text propriety of UILabel.
timerLabel.text = "\(hours):\(strMinutes):\(strSeconds).\(strFraction)"
For UILabel, text is a property & :setText is setter method for this property. So either use this property as:
timerLabel.text = "\(hours):\(strMinutes):\(strSeconds).\(strFraction)"
Or, use setter method as:
timerLabel.setText("\(hours):\(strMinutes):\(strSeconds).\(strFraction)")
But for iWatch, WKInterfaceLabel does not have any text property. You can only change the text at runtime using :setText method. For more info: see here

How to detect user inactivity in OS X writing in Swift Cocoa?

I have searched answers in stackoverflow and none of them matches my needs. I am creating time tracking app on Swift Cocoa macOS, like Hubstaff time tracking app. At the moment runs a timer and I want to detect user's inactivity after x period of time and to send a Notification that he has been Idle x period of time. I'm new to iOS and macOS development. Can I have an example of how to do it?
Here is my code:
import Cocoa
class ViewController: NSViewController {
#IBOutlet weak var label: NSTextField!
#IBOutlet weak var playImage: NSButton!
var timer : Timer!
var isTimerWorking : Bool = false
var startTime : Date!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func playPause(_ sender: NSButton) {
if isTimerWorking {
endTimer()
playImage.image = NSImage(named: NSImage.Name("play"))
sender.state = .off
} else {
startTimer()
playImage.image = NSImage(named: NSImage.Name("stop"))
sender.state = .off
}
}
func startTimer() {
startTime = Date()
timer = Timer.scheduledTimer(
timeInterval: 1.0,
target: self,
selector: #selector(self.timerCounter),
userInfo: nil,
repeats: true
)
isTimerWorking = true
}
func endTimer() {
if timer != nil {
timer.invalidate()
label.stringValue = "00:00:00"
}
isTimerWorking = false
}
#objc func timerCounter() {
let currentTime = Date().timeIntervalSince(startTime)
let hour = Int(fmod(currentTime/3600, 60))
let minute = Int(fmod(currentTime/60, 60))
let second = Int(fmod(currentTime, 60))
let hourValue = String(format:"%02d", hour)
let minuteValue = String(format:"%02d", minute)
let secondValue = String(format:"%02d", second)
label.stringValue = "\(hourValue):\(minuteValue):\(secondValue)"
}
}
In my own time tracking app I am using
var lastEvent:CFTimeInterval = 0
lastEvent = CGEventSource.secondsSinceLastEventType(CGEventSourceStateID.hidSystemState, eventType: CGEventType(rawValue: ~0)!)
print(lastEvent)
to get the user idle time.

Unable to stop timer through another viewcontroller, Swift

I developing a timer app for an apple watch.
I have two different Views at the moment. One with the actual timer (TimerController) and another with a pause-button (SwipeController).
I'm trying to stop/start the timer in the TimerController with the action from the button in the SwipeController.
Problem is that the timer stops, but the timer will not start again after hitting the button the second time.
If I press the button one time, the timer stops. If i press it again two times the timer will start again but will not stop when hitting the button again.
Any ideas of what the problem could be?
TimeController
import WatchKit
import Foundation
import UserNotifications
class TimerController: WKInterfaceController {
#IBOutlet weak var timerOutlet: WKInterfaceTimer! //
#IBOutlet weak var simple_timer_label: WKInterfaceLabel!
var myTimer : Timer?
var duration : TimeInterval = 1 //arbitrary number. 1 seconds
var isPaused = false //flag to determine if it is paused or not
var elapsedTime : TimeInterval = 0.0 //time that has passed between
var number_as_a_timer:Int = 0
var startTime = NSDate()
var dim_date = Date()
var current_minute: Int = 0
var current_hour: Int = 0
var curent_second: Int = 0
var seperate_is_paused_bool: Bool = false
override func awake(withContext context: Any?) {
super.awake(withContext: context)
start_timer()
}
func timeString(time:TimeInterval) -> String {
let hours: Int = Int(time) / 3600
let minutes: Int = Int(time) / 60 % 60
let seconds: Int = Int(time) % 60
let com = NSDateComponents()
com.minute = minutes
com.second = seconds
com.hour = hours
dim_date = NSCalendar.current.date(from: com as
DateComponents)!
self.timerOutlet.setDate(dim_date)
self.timerOutlet.start()
return String(format:"%02i:%02i:%02i", hours, minutes, seconds)
}
func start_timer() {
myTimer = Timer.scheduledTimer(timeInterval: duration, target:
self,selector: #selector(timerDone), userInfo: nil, repeats:
true)
}
#objc private func timerDone(){
//timer done counting down
if !isPaused {
number_as_a_timer += 1
let output:String = self.timeString(time:
TimeInterval(number_as_a_timer))
self.simple_timer_label.setText(output)
print(output)
}
}
override func willActivate() {
super.willActivate()
NotificationCenter.default.addObserver(self, selector:
#selector(stop_timer(notification:)), name: .stopTimer, object:
nil)
}
#objc func stop_timer(notification:NSNotification) {
// Timer is paused. so unpause it and resume countdown
if isPaused {
myTimer = Timer.scheduledTimer(timeInterval: 1,
target:self, selector: #selector(timerDone), userInfo: nil,
repeats: true)
self.isPaused = false
print("timer paused: resumming1")
} else {
isPaused = true
print("stoping timer")
//get how much time has passed before they paused it
let paused = NSDate()
elapsedTime += paused.timeIntervalSince(startTime as Date)
//stop watchkit timer on the screen
timerOutlet.stop()
//stop the ticking of the internal timer
myTimer!.invalidate()
}
}
}
extension Notification.Name {
static let stopTimer = Notification.Name("stopTimer")
}
SwipeController
import WatchKit
import Foundation
import UserNotifications
class SwipeController: WKInterfaceController {
//#IBOutlet weak var myTimer: WKInterfaceTimer!
var timer = TimerController()
var status: Bool = false
override func awake(withContext context: Any?) {
super.awake(withContext: context)
}
#IBAction func PauseButton() {
if timer.myTimer == nil {
print("timer is nil or invalidated")
print("Y: \(timer.isPaused)")
let userInfo = ["stop": true] as [String: Bool] // you
could also transfer data
NotificationCenter.default.post(name: .stopTimer, object:
nil, userInfo: userInfo)
} else {
print("empty block")
}
}
}
it looks like you aren't ever actually checking for you isPaused boolean to be true or false in your if statement when checking if your timer is paused.
if isPaused { <-----------
myTimer = Timer.scheduledTimer(timeInterval: 1,
target:self, selector: #selector(timerDone), userInfo: nil,
repeats: true)
self.isPaused = false
print("timer paused: resumming1")

Running a Timer that counts down in background when app isnt the focus? Swift

I want my countdown timer to suspend and then resume when the app leaves / returns to focus, using the time away to calculate how much time should be deducted.
I am using the app delegate file (not sure thats the right location? or if they are meant to be in the view controllers file as functions of their own?)
Issue is im getting a lot of errors such as:
Value of type 'AppDelegate' has no member 'restTimer'
Use of unresolved identifier 'nextFireDate'
Use of unresolved identifier 'selector'
restTimer was declared as a timer in my view controllers file but when i tried these blocks in that file i got an equal number of errors for unresolved identifiers
and using the following 2 code blocks
func applicationWillResignActive(_ application: UIApplication) {
guard let t = self.restTimer else { return }
nextFireDate = t.fireDate
t.invalidate()
and
func applicationDidBecomeActive(_ application: UIApplication) {
guard let n = nextFireDate else { return }
let howMuchLonger = n.timeIntervalSinceDate(NSDate())
if howMuchLonger < 0 {
print("Should have already fired \(howMuchLonger) seconds ago")
target!.performSelector(selector!)
} else {
print("should fire in \(howMuchLonger) seconds")
Timer.scheduledTimerWithTimeInterval(howMuchLonger, target: target!, selector: selector!, userInfo: nil, repeats: false)
}
}
UPDATE: Added full views code due to issue incorporating the answer
import Foundation
import UIKit
class RestController: UIViewController {
#IBOutlet weak var restRemainingCountdownLabel: UILabel!
#IBOutlet weak var setsRemainingCountdownLabel: UILabel!
#IBOutlet weak var numberOfSetsLabel: UILabel!
#IBOutlet weak var numberOfRestLabel: UILabel!
#IBOutlet weak var adjustSetsStepper: UIStepper!
#IBOutlet weak var adjustRestStepper: UIStepper!
var startDate: Date!
let startDateKey = "start.date"
let interval = TimeInterval(20)
var restTimer: Timer!
var restCount = 0
var setCount = 0
var selectedTime = 1
var selectedSets = 1
private let resignDateKey = "resign.date"
#IBAction func endSetPressed(_ sender: Any) {
if (setCount > 0){
setCount -= 1
setsRemainingCountdownLabel.text = String(setCount)
}
handleTimer()
}
#IBAction func setStepperValueChanged(_ sender: UIStepper) {
numberOfSetsLabel.text = Int(sender.value).description
self.setCount = Int(sender.value)
self.selectedSets = setCount
setsRemainingCountdownLabel.text = String(setCount)
}
#IBAction func restStepperValueChanged(_ sender: UIStepper) {
numberOfRestLabel.text = Int(sender.value).description
let timeMinSec = timeFormatted(totalSeconds: Int(sender.value)*60)
restRemainingCountdownLabel.text = timeMinSec
self.selectedTime = Int(sender.value)
restCount = self.selectedTime * 60
}
#IBAction func resetSetsButton(_ sender: Any) {
setCount = Int(adjustSetsStepper.value)
setsRemainingCountdownLabel.text = String(setCount)
}
override func viewDidLoad() {
super.viewDidLoad()
numberOfSetsLabel.text = String(selectedSets)
numberOfRestLabel.text = String(selectedTime)
createTimer(interval: interval)
NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
#objc private func willResignActive(notification: Notification) {
print("resigning")
guard restTimer.isValid else {
UserDefaults.standard.removeObject(forKey: startDateKey)
return
}
restTimer.invalidate()
UserDefaults.standard.set(Date(), forKey: startDateKey)
}
#objc private func didBecomeActive(notification: Notification) {
print("resume")
if let startDate = UserDefaults.standard.object(forKey: startDateKey) as? Date {
let elapsed = -startDate.timeIntervalSinceNow
print("elpased time: \(elapsed) remaining time: \(interval - elapsed)")
if elapsed > interval {
timerUp()
} else {
createTimer(interval: interval - elapsed)
}
}
}
private func createTimer (interval: TimeInterval) {
restTimer = Timer.scheduledTimer(withTimeInterval: interval , repeats: false) {[weak self] _ in
self?.timerUp()
}
startDate = Date()
}
private func timerUp() {
print("At least \(interval) seconds has elapsed")
}
func handleSets() {
if (setCount > 0) {
self.restCount = self.selectedTime * 60
}
handleTimer()
}
func handleTimer() {
if (restTimer?.isValid ?? false) {
restTimer?.invalidate()
restTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(RestController.updateTimer), userInfo: nil, repeats: true)
} else {
restTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(RestController.updateTimer), userInfo: nil, repeats: true)
}
}
func updateTimer() {
if (restCount > 0){
restCount -= 1
} else if (restCount == 0){
restTimer?.invalidate()
}
restRemainingCountdownLabel.text = timeFormatted(totalSeconds: restCount)
}
func timeFormatted(totalSeconds: Int) -> String {
let seconds: Int = totalSeconds % 60
let minutes: Int = (totalSeconds / 60) % 60
return String(format: "%02d:%02d", minutes, seconds)
}
I think you cannot rely on the fact that the app will remain in memory while it is in the background. Thus, you should archive all the data you need to recreate the timer at the exact point.
For example, in applicationWillResignActive
UserDefaults.standard.set(value: t.nextFireDate forKey:"NextFireDate")
and in applicationWillEnterForeground
if let fireDate = UserDefaults.standard.object(forKey: "NextFireDate") {
// setup a timer with the correct fire date
}
You don't have to use the AppDelegate for this because it also posts notifications. You can use the AppDelegate if you want. Here is code using notifications:
class ViewController: UIViewController{
private let startDateKey = "start.date"
private let interval = TimeInterval(20)
private var startDate: Date!
private var timer: Timer!
override func viewDidLoad() {
super.viewDidLoad()
createTimer(interval: interval)
NotificationCenter.default.addObserver(self, selector: #selector(willResignActive), name: NSNotification.Name.UIApplicationWillResignActive, object: nil)
NotificationCenter.default.addObserver(self, selector: #selector(didBecomeActive), name: NSNotification.Name.UIApplicationDidBecomeActive, object: nil)
}
deinit {
NotificationCenter.default.removeObserver(self)
}
#objc private func willResignActive(notification: Notification) {
print("resigning")
guard timer.isValid else {
UserDefaults.standard.removeObject(forKey: startDateKey)
return
}
timer.invalidate()
UserDefaults.standard.set(Date(), forKey: startDateKey)
}
#objc private func didBecomeActive(notification: Notification) {
print("resume")
if let startDate = UserDefaults.standard.object(forKey: startDateKey) as? Date {
let elapsed = -startDate.timeIntervalSinceNow
print("elpased time: \(elapsed) remaining time: \(interval - elapsed)")
if elapsed > interval {
timerUp()
} else {
createTimer(interval: interval - elapsed)
}
}
}
private func createTimer (interval: TimeInterval) {
timer = Timer.scheduledTimer(withTimeInterval: interval , repeats: false) {[weak self] _ in
self?.timerUp()
}
startDate = Date()
}
private func timerUp() {
print("At least \(interval) seconds has elapsed")
}
}