每天在特定时间重置特定值

Reset certain values every day at certain time

在我的应用程序中,我有一组待办事项对象。每天的某个时间,比方说下午 13 点,待办事项数组必须被修改。 每天用什么功能可以触发这个事件?

当应用程序在前台运行时,您可以设置一个计时器,在超过特定时间阈值时触发。 如果应用程序在后台运行时,您可以在下次启动应用程序时检查是否已超过阈值,然后再进行修改。

例如,要添加计时器,请在您的 AppDelegate 中添加:

    private var myTimer: Timer? 

func applicationWillResignActive(_ application: UIApplication) {
    myTimer?.invalidate()
}

func applicationDidBecomeActive(_ application: UIApplication) {
    //Scheduling for 1 PM (13:00)
    var dateComponents = Calendar.current.dateComponents([.minute, .hour, .month, .day, .year], from: Date())
    dateComponents.hour = 13
    dateComponents.minute = 00
    dateComponents.timeZone = TimeZone.current

    if let timerDate = Calendar.current.date(from: dateComponents) {
        myTimer = Timer(fireAt: timerDate, interval: 0, target: self, selector: #selector(timerFired), userInfo: nil, repeats: false)
    }

    if let myTimer = myTimer {
        RunLoop.current.add(myTimer, forMode: RunLoopMode.commonModes)
    }
}

func timerFired() {
   //Do you update here
}

您可以在 applicationDidBecomeActive 方法中添加一个额外的检查,以检查您的修改是否已经在当天完成,以防在应用程序处于后台或非活动状态时超过阈值。