Skip to content

Commit

Permalink
better way of calculating the remaining time
Browse files Browse the repository at this point in the history
  • Loading branch information
tgymnich committed Jun 29, 2020
1 parent e9cc081 commit 1ecde4d
Show file tree
Hide file tree
Showing 2 changed files with 6 additions and 4 deletions.
5 changes: 3 additions & 2 deletions Sources/OTPKit/TOTP.swift
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,10 @@ public class TOTP: OTP {
@available(OSX 10.12, iOS 10.0, tvOS 10.0, watchOS 3.0, *)
private lazy var timer: Timer = {
let timeForNextPeriod = Date(timeIntervalSince1970: TimeInterval((counter + 1) * period))
let timer = Timer(fire: timeForNextPeriod, interval: TimeInterval(period), repeats: true) { [weak self] timer in
let timer = Timer(fire: timeForNextPeriod, interval: TimeInterval(period), repeats: true) { [weak self] _ in
guard let self = self else { return }
let timeRemaining = timer.fireDate.timeIntervalSince(Date())
let timeForNextPeriod = Date(timeIntervalSince1970: TimeInterval((self.counter + 1) * self.period))
let timeRemaining = timeForNextPeriod.timeIntervalSince(Date())
NotificationCenter.default.post(name: .didGenerateNewOTPCode, object: self, userInfo: [UserInfoKeys.code : self.code(), UserInfoKeys.timeRemaining: timeRemaining])
}
timer.tolerance = 1
Expand Down
5 changes: 3 additions & 2 deletions Sources/OTPKit/TOTPPublisher.swift
Original file line number Diff line number Diff line change
Expand Up @@ -40,9 +40,10 @@ public extension TOTP {
private var totp: TOTP
private lazy var timer: Timer = {
let timeForNextPeriod = Date(timeIntervalSince1970: TimeInterval((totp.counter + 1) * totp.period))
let timer = Timer(fire: timeForNextPeriod, interval: TimeInterval(totp.period), repeats: true) { [weak self] timer in
let timer = Timer(fire: timeForNextPeriod, interval: TimeInterval(totp.period), repeats: true) { [weak self] _ in
guard let self = self else { return }
let timeRemaining = timer.fireDate.timeIntervalSince(Date())
let timeForNextPeriod = Date(timeIntervalSince1970: TimeInterval((self.totp.counter + 1) * self.totp.period))
let timeRemaining = timeForNextPeriod.timeIntervalSince(Date())
let token = TOTPToken(code: self.totp.code(), timeRemaining: timeRemaining)
_ = self.subscriber?.receive(token)
}
Expand Down

0 comments on commit 1ecde4d

Please sign in to comment.