Pass a Timer through Controllers

I have an app that manages orders.

It has a tab controller with three tabs, the second tab submits the order and the third tab shows all the ongoing orders once they are submitted.

Each order generates an estimated time remaining for delivery.

On the third tab, when showing the ongoing orders, there is a progress view which fills up as the time for delivery from the order elapses.

How can I fire a timer on the second tab when the user submits the order, and keep the progress view on the third tab updated with such timer?

I also wish for the user to be able to close the app and have the timer run in the background

What is a possible workaround for this?

There may be a simple way to achieve the expected result. I would try the following:

  • In the class or struct that defines an order, create a DispatchTime property
  • initialise it = .now() when customer submits the order (in second VC)
  • in third VC, use it to display any remaining time you need to show.

I also wish for the user to be able to close the app and have the timer run in the background

The timer will not run in the background, but here is a technique that you could use:

Add a mechanism to detect when the app is entering the background, or foreground

On backgrounding:

  • If your timer is live...
  • Convert it to a notification (calculate the fire date from the timer expiry)
  • Cancel the timer

If the timer expires while the app is backgrounded, the user will see the notification

On foregrounding:

  • Remove pending notifications
  • Restart the timer, if it has not expired
Pass a Timer through Controllers
 
 
Q