swift 如何使变量的值每天重置

px9o7tmv  于 2022-11-28  发布在  Swift
关注(0)|答案(1)|浏览(111)

我想做一个锻炼应用程序来帮助用户跟踪他们的日常锻炼,我有一个变量exerciseTime,我想每天重置它。有什么方法可以做到这一点吗?
变量存储在应用存储@AppStorage("exerciseTime") var exerciseTime = 0.0中,并连接到计时器。

Text("Time: \(format(seconds: timerStruct.countdownTimer))")
                .padding()
                .onReceive(timer) { _ in
                    if timerStruct.countdownTimer > 0 && timerStruct.timerRunning == true {
                        timerStruct.countdownTimer -= 1
                        exerciseTime += 1.0
                    } else {
                        timerStruct.timerRunning = false
                        if timerStruct.countdownTimer <= 0, timerStruct.timerRunning == false {
                            timerStruct.isAlertpresented = true
                            reset()
                        }
                    }
umuewwlo

umuewwlo1#

此函数用于检查当前日期是否与UserDefaults中保存的日期在同一天
只要在应用程序激活时始终调用即可

func isNewDay() -> Bool {
    let defaults = UserDefaults.standard
    let now = Date.now
    if let savedDate = defaults.object(forKey: "currentDate") as? Date,
       Calendar.current.compare(savedDate, to: now, toGranularity: .day) == .orderedSame {
        return false
    }
    defaults.set(now, forKey: "currentDate")
    return true
}

相关问题