How to prevent an iOS app from sleeping when sent to the background

iOS can get really annoying when it comes to conserving battery power. It makes sense - if some app drains battery due to poor design the users will most likely blame the device for having a crappy battery, not the app. By default iOS hibernates your app whenever the user presses the Home button (or switches to another app). To prevent that the app must declare itself as one that needs background access.

There are several modes the app can be launched in, you can see those in Project settings -> Target -> Capabilities -> Background Modes. One mode, specifically "Audio, AirPlay and Picture in Picture" permits the app run constantly, even when sent to the background. The app will run as long as some AVFoundation object is playing.

BackgroundCaffeine tricks iOS into thinking the app actually needs to be active indefinitely, even when sent to the background (by playing a silent 1-sec long audio and setting the AVPlayer's properties in a way the player remains active even after finishing playing the silent audio, preventing the app from sleeping).

Call a static method +preventAppFromSleepingInBackground to enable backgrounding. To disable backgrounding call +allowAppToSleepWhenInBackground. Do not forget to add 1secofsilence.mp3 to your project. The silent audio doesn't interfere with anything else played by the system or by your app and remains unnoticeable to the user.

Warning: this approach is a kind of a hack and unless your app really requires playing some audio or video in the background it is prone to rejection from the App Store. It was good enough for my in-house app though. The app never went to sleep unless I explicitly terminated it (by swiping it up in Task Manager).