timer - I need a reliable StopWatch in Swift 3 -
i need reliable stopwatch in swift 3. came based on example found on ...
import foundation class stopwatch { public private(set) var seconds:double = 0 public var milliseconds: double { return seconds * 1000 } private weak var timer:timer? private var starttime:double = 0 public private(set) var started = false public func start() { if started { return } started = true starttime = date().timeintervalsincereferencedate timer = timer.scheduledtimer(withtimeinterval: 0.05, repeats: true) { timer in if !self.started { return } self.seconds = date().timeintervalsincereferencedate - self.starttime print("seconds: \(self.seconds)") } print("started") } public func stop() { if !started { return } timer?.invalidate() started = false print("stopped") } }
but doesn't seem work reliably. fetching seconds staying @ 0 or in other cases when accessing seconds don't start 0. wrong code?
it's threading issue. if ui involved have make sure ui related code runs on main thread.
the variable started
redundant. checking timer nil
same.
this code adds dispatchqueue.main
block. put code update ui block
class stopwatch { public private(set) var seconds:double = 0 public var milliseconds: double { return seconds * 1000 } private weak var timer : timer? private var starttime : double = 0 private var timerisrunning : bool { return timer != nil } public func start() { if timerisrunning { return } starttime = date().timeintervalsincereferencedate timer = timer.scheduledtimer(withtimeinterval: 0.05, repeats: true) { timer in self.seconds = date().timeintervalsincereferencedate - self.starttime print("seconds: \(self.seconds)") dispatchqueue.main.async { // on main thread } } print("started") } public func stop() { if !timerisrunning { return } timer!.invalidate() timer = nil print("stopped") } }
Comments
Post a Comment