Search code examples
iosswifttimer

Swift 4 - Start Timer at Precise Clock Time in the Future


I've been stuck with this and searching up for answers.

I want a timer to start at an exact time in the future. Here is the scenario:

  1. User selects time with a date picker. Say he picks 9:00PM
  2. It's currently 3:45PM, so the timer should start in 5 hours and 15 minutes.
  3. how can I get the timer to start at that exact time?

Any help would be very appreciated.


Solution

  • No, there is no way to do this in iOS. Apps get suspended quite quickly after the user stops using them (switches to another app or locks the device.) Being suspended means you don't get any CPU time, and can be terminated at any time after that without further warning.

    You're only allowed to run in the background for few minutes except under very specific circumstances (if you're a turn-by-turn navigation app or a music playing app.)

    You'd only be able to start a timer at a specific moment if you were actively running at that moment, and you don't have any way to make that happen.

    The best I can think of would be to set up a local notification to fire at the desired time. That would display a message to the user and let the user tap to either open your app or dismiss the notification. If the user tapped to open your app then you would get a chance to start your timer.