Using Swift5.2, Xcode11.4 and iOS13.4,
I try to run Audio at a certain time in the future.
Moreover, the App is in background mode (and the App is completely closed).
The Audiosession must be set up to keep the App responsive and the Audio sound shall start at delay-times up to 1 year.
I tried:
A) The Background Mode "Audio, AirPlay and Picture in Picture" is added:
B) The AudioSession and AVAudioPlayer is configured as follows:
import AVKit
var audioPlayer: AVAudioPlayer?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]?)
-> Bool {
do {
//set up audio session
let audioSession = AVAudioSession.sharedInstance()
try audioSession.setCategory(.playback, mode: .default, options: [.defaultToSpeaker, .duckOthers])
try audioSession.setActive(true)
// Start AVAudioPlayer
try audioPlayer = AVAudioPlayer(contentsOf: alertSound)
audioPlayer!.numberOfLoops = -1 // play endlessly
audioPlayer!.prepareToPlay()
let currentAudioTime = audioPlayer!.deviceCurrentTime
let delayTime: TimeInterval = 20.0 // here as an example, we use 20 seconds delay
audioPlayer!.play(atTime: currentAudioTime + delayTime) // delayTime is the time after which the audio will start
}
catch {
print(error)
}
return true
}
.
There are two problems with the code above:
the session-Category
.playback
does cause the errorError Domain=NSOSStatusErrorDomain Code=-50 "(null)"
the sound only plays when App is in foreground or in background-with-app-still-alive - but unfortunately not in background-with-app-completely-closed
Here my questions:
Why is session-category
.playback
not working under iOS13.4 ?Why is the sound not playing when the app is completely closed ? (background-mode) ???
Is it enough to just set the Background-mode tag "Audio, AirPlay and Picture in Picture" ? Or is there some code needed in order to fully implement background mode ? Is there something missing in code in order to make the sound future-start in a fully closed app ?
As for Question 1:
--> I've found a workaround and set the session-Category to .playAndRecored
- after that the error goes away
try audioSession.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .duckOthers])
The question still remains: why is .playback not working ? And what is the difference between .playback
and .playAndRecord
?