When I'm on the simulator and click the button it keeps adding 50. I think it may not be saving "latestTerminationDate", or maybe not pulling it. Thank you for any help
@IBOutlet weak var coalRunButton: UIButton!
var coalMayham = 1
@IBAction func coalRunButton(_ sender: Any) {
if let buttonPress = UserDefaults.standard.object(forKey: "buttonPress") as? Date,
let terminationDate = UserDefaults.standard.object(forKey: "latestTerminationDate") as? Date {
var terminationDuration = buttonPress.timeIntervalSince(terminationDate)
if terminationDuration >= 86400 {
_ = 86400
do { UserDefaults.standard.set(Date(), forKey: "latestTerminationDate")
UserDefaults.standard.synchronize()
let dailyCoalAccumulate = ((Int(terminationDuration)) * coalMayham) + Int(coalPile.text!)!
coalPile.text = String(dailyCoalAccumulate)
UserDefaults.standard.set(Data(), forKey:"totalCoal")
}
} else {
terminationDuration = 50
UserDefaults.standard.set(Date(), forKey: "latestTerminationDate")
UserDefaults.standard.synchronize()
let dailyCoalAccumulate = ((Int(terminationDuration)) * coalMayham) + Int(coalPile.text!)!
coalPile.text = String(dailyCoalAccumulate)
UserDefaults.standard.set(Data(), forKey:"totalCoal")
}
} else {
let terminationDuration = 40
UserDefaults.standard.set(Date(), forKey: "latestTerminationDate")
UserDefaults.standard.synchronize()
let dailyCoalAccumulate = ((Int(terminationDuration)) * coalMayham) + Int(coalPile.text!)!
coalPile.text = String(dailyCoalAccumulate)
UserDefaults.standard.set(Data(), forKey:"totalCoal")
}
}
This line of code:
let terminationDate = UserDefaults.standard.object(forKey: "latestTerminationDate") as? Date
Is not returning what you think it does. Because in this line of code:
UserDefaults.standard.set(Date(), forKey: "latestTerminationDate")
the Date()
you are entering looks like: "2018-10-04 15:30:22 +0000"
which can not be compared to 86400
For that reason:
if terminationDuration >= 86400
fails and reverts to:
else {
terminationDuration = 50
EDIT
FIX EXAMPLE:
func getMillisecondsNow() -> Int64{
let currentDate = Date()
return getMillisecondsFromDate(date: currentDate)
}
func getMillisecondsFromDate(date: Date) -> Int64{
var d : Int64 = 0
let interval = date.timeIntervalSince1970
d = Int64(interval * 1000)
return d
}
func getTimeDifferenceFromNowInMilliseconds(time: Int64) -> Int64{
let now = getMillisecondsNow()
let diff: Int64 = now - time
return diff
}
This will be in milliseconds so you will need to use 86400000 (milliseconds in 24 hrs) instead of 86400 (seconds in 24 hrs)
Now in your code simply use this to save the termination time in Milliseconds:
let now = getMillisecondsNow()
UserDefaults.standard.set(now, forKey: "latestTerminationDate")
and this code to retrieve and get the time difference in Milliseconds:
let terminationTime = UserDefaults.standard.object(forKey: "latestTerminationDate") as? Int64
let timeDiff = getTimeDifferenceFromNowInMilliseconds(time: terminationTime)
if timeDiff >= 86400000 {
}
else {
}