Reputation: 137
I'm trying to make an alarm clock in swift that will play an audio stream at a certain time by using a background notification. How do I do it?
There are several alarm apps on the app store that are able to something like this. One of the apps called "bedr radio" is able to stream a radio station for a certain amount of time which you select when you create the alarm. It even has the option of never-ending the stream until you stop it. The thing which I'm trying to figure out is how it is called when my phone is locked or I'm not in the app. I tried putting my phone into airplane mode and I only receive a local notification. Upon receiving it the app checks to see if it can start a stream if it cants it will play a backup alarm. A background function is called to check if it can or can't play the stream and responds accordingly.
Another alarm app called "Alarm Clock HD" is a little different. When the alarm is set off the volume will slowly increase even while out of the app or with the phone locked. I also tried putting my phone into airplane mode and setting off the app. It also will perform a background function without the use of a remote notification.
My overarching question is this; How do these apps accomplish calling a function in the background while the app is closed or even with the phone being locked?
In my app I use willPresentNotification to call a function when my app is in the foreground. How to I called a function after a notification when the app is in the background? I know that remote notifications has a method to do this, however, I prefer not to use a server unless I can't find an easier solution.
How do I accomplish calling a function in the background like these apps do? I'm open to any and all explanations on how this works and how I can implement this into my app.
Upvotes: 3
Views: 2069
Reputation: 1249
You could use a UNNotificationRequest with a UNCalendarNotificationTrigger. This would allow you to set the date and time that the local notification will fire. After getting notification permission from the user, set up this notification and make sure your AppDelegate has code in place to handle system notifications.
Upvotes: 0