Created
July 22, 2016 00:30
-
-
Save AnselmeKotchap/dabac341fd4b7646dad5cf47037e1775 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//While I'm not sure the details of your implementation, I'd probably recommend storing the start time as an NSDate(), | |
//then instead of incrementing/decrementing from an Integer/Float/Double, you can just calculate the time since the initial | |
//date, then remove that amount of time from your totalTime. That way when the app reopens, the time calculation is always | |
//correct. The calculation for determining how long ago an NSDate() is so light that it'll be nearly instantaneous. | |
import UIKit | |
class Timer { | |
private var startTime: NSDate? // Recorded when the user starts the timer. | |
private var totalTime: Double = 0.0 // If you're counting down, this is the total time designated by the user (e.g. 20 mins) | |
private var currentTime: Double = 0.0 // Displayed time visible to user. | |
private func startTimer() { | |
startTime = NSDate() | |
} | |
private func updateTimer() { | |
let timeDifference = startTime!.timeIntervalSinceNow // See http://stackoverflow.com/questions/4084341/how-to-calculate-time-in-hours-between-two-dates-in-ios | |
if timeDifference >= totalTime { | |
currentTime = 0.0 | |
} | |
else { | |
currentTime = totalTime - timeDifference | |
} | |
} | |
} | |
//source: https://teamtreehouse.com/community/swift-weather-app-reload-data |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment