I am stuck a point from days. Basically, i am developing an application which play some audios
to guide user (user can not control these audios no play/pause) and with paying audios it also using accelerometer
to get data and calculate some results from this data with regular interval.
Means i am playing some audios and then start accelerometer about 4 times alternatively
Every thing is working as expected but when application enters into background application is kept alive for some time and the OS terminate/kill application.
Basically this whole flow take about 6 to 7 minutes at-least meaning that my application needed to alive in background mode at-least 7 minutes. I have seen stackOverFlow questions but not success.
What i am using when user start
self.backgroundTaskID = UIApplication.shared.beginBackgroundTask (withName: "Finish Network Tasks") {
// End the task if time expires.
UIApplication.shared.endBackgroundTask(self.backgroundTaskID!)
self.backgroundTaskID = UIBackgroundTaskIdentifier.invalid
}
self.startForFirsPhase()
When first phase over I start second phase and third phase after end of previous
- I have added
Required background modes
ininfo.plist
Background Process
andAudio, AirePlay and Picture in Picture
in theSigning & Capabilities
and code to play audios is blow
func play(name: String, volumeLevel: Float? = 1) {
// print("NameForAudio: ", name)
guard let path = Bundle.main.path(forResource: name, ofType: nil) else {
print("can not find path")
return
}
let url = URL(fileURLWithPath: path)
do {
try AVAudioSession.sharedInstance().setCategory(.playback)
try AVAudioSession.sharedInstance().setActive(true, options: .notifyOthersOnDeactivation)
self.audioPlayer = try AVAudioPlayer(contentsOf: url)
self.audioPlayer.volume = volumeLevel ?? 1
self.audioPlayer!.play()
} catch {
print("some thing went wrong Name: \(error)")
}
}
all the audios are liked with the accelerometer I play some audio after one an other using DispatchQueue.main.asyncAfter(deadline: .now() + durationOfPreviousAudio)
What i am trying to do is. I play some audios one after another then start accelerometer to get some motion sensor data for 1 minute and then i again want to play some audio after that which do not play without UIApplication.shared.beginBackgroundTask
.