iOS 14 indefinite background time

Viewed 68

once again the problem of background processing time on iOS has come up. The older way of playing audio or doing VoIP seems to work only if you are doing stuff relating to it, but if you spawn a new thread(doing computation) it will kill the app. This seems to be new in iOS >14 as 13 works for the old way. So as it's been a while since this question has been answered and the prior answer no longer works, does anyone know how to do this. I understand that Apple won't approve my app if I do this, I am not planning to put it on the App store.

This is the code I have, just in case I am doing something wrong...

class ViewController: UIViewController, UITextFieldDelegate,AVAudioPlayerDelegate  {

    var backgroundTask = UIBackgroundTaskIdentifier.invalid

    var audioPlayer: AVAudioPlayer?
    
    func registerBackgroundTask() {
        backgroundTask = UIApplication.shared.beginBackgroundTask { [weak self] in
            self?.endBackgroundTask()
        }
        assert(backgroundTask != UIBackgroundTaskIdentifier.invalid)
    }
       
    func endBackgroundTask() {
        print("Fail!!!")
        UIApplication.shared.endBackgroundTask(backgroundTask)
        backgroundTask = UIBackgroundTaskIdentifier.invalid
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        registerBackgroundTask()
        do {
            let aSound = URL(fileURLWithPath: Bundle.main.path(forResource: "nothing", ofType: "mp3")!)
            audioPlayer = try AVAudioPlayer(contentsOf: aSound)
            do {
                try AVAudioSession.sharedInstance().setCategory(.playback, mode: .default)
                try AVAudioSession.sharedInstance().setActive(true)
            } catch {
            }
            audioPlayer!.setVolume(1.0, fadeDuration: CFTimeInterval())
            audioPlayer!.numberOfLoops = -1
            audioPlayer!.prepareToPlay()
            audioPlayer!.delegate = self
            audioPlayer!.play()
        } catch {
            print("OOPS!")
        }
    }
}
0 Answers
Related