Search code examples
iosswiftrealm

What would be a good way to handle "snoozed" functions?


I've tried a few solutions so far but I'm not sure if there is a "right" way. I'm working on a todo list with a snooze function. Each task has a "wake from snooze" time when I need to run a function to move it into a different list.

I've tried looping through each task and moving it when viewWillAppear and/or viewDidAppear runs. This generally works but seems to misfire occasionally and wouldn't happen while the app is running and the user isn't switching views.

I've tried using the Timer() function to move items at the actual specific times which only works while the app is running.

I've tried moving the items in the background using performFetchWithCompletionHandler and checking every hour.

Anything else I should try to make this run more smoothly? Is it a combination of all of these? If that's the case, how would I make sure that I'm not trying to move items twice at the same time?


Solution

  • In general the question seems to be how to ensure that something happens at a certain date-time.

    1. Work out what the target date-time is and write it down somewhere stable (a file, user defaults, whatever) along with what has to happen then.

    2. Watch the clock. A timer that fires every minute will probably be good enough; just look at the clock and see if that time has passed. If it has, do the thing and erase the info saying that this thing needs to happen at this date-time.

    3. If the app goes into the background, stop the timer.

    4. When the app comes to the foreground again, check your date-time.

      • If the time has passed, do the thing and erase the info saying that this thing needs to happen at this date-time.

      • If not, start the timer again and keep watching the clock.