如何在Swift UI中每24小时重置一个值?

如何在Swift UI中每24小时重置一个值?,swift,xcode,timer,swiftui,nsdate,Swift,Xcode,Timer,Swiftui,Nsdate,我正在尝试每24小时将值设置为0,无论用户是否已打开应用程序。我知道我的应用程序不能在后台运行计时器,那么如何让该值每24小时自动重置一次 我已尝试保存用户上次运行应用程序的时间,并检查它是否在当前时间的24小时内,但如果在24小时内,则不会重置该值。(另外,当我在UserDefaults to Date()中保存一个变量并打印它时,出于某种原因,它会给我未来16小时的时间。)即使我使用NSDate,我想我仍然会有这个问题 感谢您的阅读,我非常感谢您的建议:)您真的需要在24小时内重置应用程序值

我正在尝试每24小时将值设置为0,无论用户是否已打开应用程序。我知道我的应用程序不能在后台运行计时器,那么如何让该值每24小时自动重置一次

我已尝试保存用户上次运行应用程序的时间,并检查它是否在当前时间的24小时内,但如果在24小时内,则不会重置该值。(另外,当我在UserDefaults to Date()中保存一个变量并打印它时,出于某种原因,它会给我未来16小时的时间。)即使我使用NSDate,我想我仍然会有这个问题


感谢您的阅读,我非常感谢您的建议:)

您真的需要在24小时内重置应用程序值吗?您是否只想检查自上次重置值以来是否已超过24小时,并在每次应用程序启动时重置是否已超过24小时?如果您不需要在特定时间重置它,那么您可以将以下代码添加到您的应用程序代理

    if UserDefaults.standard.bool(forKey: "didLaunchBefore") == false{
  //only runs the first time your app is launched
            UserDefaults.standard.set(true, forKey: "didLaunchBefore")
  //sets the initial value for tomorrow
            let now = Calendar.current.dateComponents(in: .current, from: Date())
            let tomorrow = DateComponents(year: now.year, month: now.month, day: now.day! + 1, hour: now.hour, minute: now.minute, second: now.second)
            let date = Calendar.current.date(from: tomorrow)
            UserDefaults.standard.set(date, forKey: "tomorrow")
        }
        if UserDefaults.standard.object(forKey: "tomorrow") != nil{//makes sure tomorrow is not nil
            if Date() > UserDefaults.standard.object(forKey: "tomorrow") as! Date {// if todays date is after(greater than) the 24 hour period you set last time you reset your values this will run
  // reseting "tomorrow" to the actual tomorrow
                let now = Calendar.current.dateComponents(in: .current, from: Date())
                let tomorrow = DateComponents(year: now.year, month: now.month, day: now.day! + 1, hour: now.hour, minute: now.minute, second: now.second)
                let date = Calendar.current.date(from: tomorrow)
                UserDefaults.standard.set(date, forKey: "tomorrow")
                //reset your values here
            }
        }

尝试使用UserDefaults保存日期:

UserDefaults.standard.set(Date(), forKey:"savedTime")
并检查该值是否必须设置为0:

if let date = UserDefaults.standard.object(forKey: "savedTime") as? Date {
   if let diff = Calendar.current.dateComponents([.hour], from: date, to: Date()).hour, diff >= 24 {
      //Set value to 0
   }
}