当我在模拟器上,点击按钮,它不断增加50。我认为这可能不是在保存“最晚终止日期”,也可能不是在拉它。谢谢你的帮助

@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")
   }
}

最佳答案

这行代码:

let terminationDate = UserDefaults.standard.object(forKey: "latestTerminationDate") as? Date

不是你想的那样。因为在这行代码中:
UserDefaults.standard.set(Date(), forKey: "latestTerminationDate")

您输入的Date()看起来像:“2018-10-04 15:30:22+0000”
比不上86400
因此:
if terminationDuration >= 86400

失败并还原为:
 else  {
        terminationDuration =  50

编辑
修复示例:
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
}

这将以毫秒为单位,因此您需要使用86400000(24小时内为毫秒),而不是86400(24小时内为秒)
现在在您的代码中,只需使用此命令以毫秒为单位保存终止时间:
let now = getMillisecondsNow()
UserDefaults.standard.set(now, forKey: "latestTerminationDate")

获取时间差(毫秒)的代码:
let terminationTime = UserDefaults.standard.object(forKey: "latestTerminationDate") as? Int64
let timeDiff = getTimeDifferenceFromNowInMilliseconds(time: terminationTime)

if timeDiff >= 86400000 {
}
else {
}

10-08 06:20