I'm writing a simple alarm clock application in Swift 3.
The way I'm writing this application is, I have a timer
set for 60 seconds, that every time it fires, it checks if an alarm is set for that time, and then fires the alarm.
The purpose of this application is to turn on my HomeKit connected lights when it fires. This is why I can't take the approach of setting a local notifications, because when that executes there's no way to run the code of turning on the lights.
I have this application set to run in the background (as much as apple will allow it), in the way that if the application is open when you lock the phone, it will continue running.
This works perfectly in the simulator, even for long amounts of time. This also works on my phone, when I don't set the alarm for too far ahead.
However, when I leave the application on my phone overnight, it rarely works.
To debug this, I created a text file in the application, and set the timer
so that when it checks the time, it also writes the time to that text file.
I did this so I could see if the timer would continue to run overnight, for the full night.
Here were my results.
Last night, I went to bed at 4 am, and set an alarm for 8am. (I know that's great, haha) In the text file, when I left the application running, The timer continued to run for a good half hour, with every minute, logging the correct time.
To make it easier to read, I uploaded a screenshot.
https://i.stack.imgur.com/9bV5S.jpg
Notice how it was logging every minute.
However, later on in the night, the timer stopped firing every minute, and started becoming more sporatic.
Notice how the timer fired at 5:13 am
, then 5:25 am
, 5:53
, and so on.
This has happened for the past couple nights, and I don't know what to do.
I'm not receiving any texts, or anything else that I would think would cause the timer thats supposed to firing every minute, fire every half hour randomly.
Is there anything I can do to make sure that this timer fires every minute reliably?
If you made it this far, thanks so much! This is my first application and It's a struggle working around Apple's background restrictions.
Thanks!