Many alarm apps managed to play sound with locked screen after several hours (examples: Rise, Wave alarm clock)
All you need to do is set the alarm and lock your screen while the app is open and an alarm will go off hours after the screen has been locked.
I managed to figure out how to play audio with AVPlayer while my device is locked:
Set background capabilities to audio
Set 'Application does not run in background' to YES
Code:
do { try AVAudioSession.sharedInstance().setCategory(AVAudioSessionCategoryPlayback) print("AVAudioSession Category Playback OK") do { try AVAudioSession.sharedInstance().setActive(true) print("AVAudioSession is Active") } catch let error as NSError { print(error.localizedDescription) } } catch let error as NSError { print(error.localizedDescription) }
When I try to set a NSTimer or use dispatch_after to run the code that plays my audio file and lock my iPhone the Timer stops pretty quickly because apparently the app gets inactive after just a few seconds (But only when I start the App from the home screen and doesn't when I run the App from xcode, btw)
How do those alarm clock apps manage to delay audio?