Basically, I have an application where the user can set the time of the first notification, and the following ones will happen repeatedly. For example, I want to be notified every 8 hours, but the first notification will not be from now on. So I need to create 2 notifications, one for the first one, and as soon as the first one goes off, I need to set a new notification every 8 hours.
A practical example: I will take my medicine at 8 o’clock in the morning, but now it’s 5 o’clock, and I want to be notified every 8 hours. The first alarm must be for 8 o’clock from 8 o’clock, that is, 4 o’clock. For that, I made a logic:
However, the other alarms cannot have the same time as the first one, because, as in the previous example, if I left the same trigger, the alarms would be 11 hours, not 8. I need the first to be 11 hours, and the subsequent numbers of 8 in the example.
I already have the code for the first alarm, however, I can’t think of a way to create the subsequent ones, which will keep repeating according to the desired time, for example, 8 in 8, 12 in 12
2
Answers
Use a repeating
UNCalendarNotificationTrigger
for each separate time of day. In your case, that means use three triggers (and therefore three requests): one each at 8, 16, and 0 hours. You don’t need to add a separate request for the soonest occurrence.You need to setup a
BGAppRefreshTask
, which will tell the System to periodically wake your app to run in the Background to do something in about 30 seconds, then app is Suspended.You can set a Refreshing Task every 6 hours to check and make a new Local Push Notification if needed.
Here is the guide: https://developer.apple.com/documentation/uikit/app_and_environment/scenes/preparing_your_ui_to_run_in_the_background/using_background_tasks_to_update_your_app
When you setup your local notification:
Function in your AppDelegate.swift