From 3ac3f23c0f76cde601db6ef23a3f6e3c3b714f49 Mon Sep 17 00:00:00 2001 From: Daniil Vinogradov Date: Mon, 18 Nov 2024 22:58:48 +0100 Subject: [PATCH] Background downloading attempt fix --- .../AudioBackgroundService.swift | 40 ++++++++++++++----- 1 file changed, 31 insertions(+), 9 deletions(-) diff --git a/iTorrent/Services/BackgroundService/AudioBackgroundService.swift b/iTorrent/Services/BackgroundService/AudioBackgroundService.swift index 5ac9226f..268b1d00 100644 --- a/iTorrent/Services/BackgroundService/AudioBackgroundService.swift +++ b/iTorrent/Services/BackgroundService/AudioBackgroundService.swift @@ -20,16 +20,15 @@ extension AudioBackgroundService: BackgroundServiceProtocol { func start() -> Bool { guard !isRunning else { return true } - guard playAudio() else { return false } startBackgroundTask() NotificationCenter.default.addObserver(self, selector: #selector(interruptedAudio), name: AVAudioSession.interruptionNotification, object: AVAudioSession.sharedInstance()) return true } func stop() { - stopBackgroundTask() NotificationCenter.default.removeObserver(self, name: AVAudioSession.interruptionNotification, object: nil) - player?.stop() + stopBackgroundTask() + stopAudio() } func prepare() async -> Bool { true } @@ -62,6 +61,7 @@ private extension AudioBackgroundService { try player = AVAudioPlayer(contentsOf: alertSound) player?.volume = 0.01 + player?.numberOfLoops = -1 player?.prepareToPlay() player?.play() return true @@ -71,15 +71,23 @@ private extension AudioBackgroundService { } } + func stopAudio() { + player?.stop() + } + func startBackgroundTask() { - stopBackgroundTask() - - guard BackgroundService.isBackgroundNeeded else { return } + guard BackgroundService.isBackgroundNeeded else { return } - playAudio() - backgroundTask = UIApplication.shared.beginBackgroundTask(expirationHandler: { [unowned self] () -> Void in + Task { + playAudio() + stopBackgroundTask() + + backgroundTask = await UIApplication.shared.beginBackgroundTask() + stopAudio() +// await print(UIApplication.shared.backgroundTimeRemaining) + try await Task.sleep(for: .seconds(10)) startBackgroundTask() - }) + } } func stopBackgroundTask() { @@ -89,3 +97,17 @@ private extension AudioBackgroundService { } } } + +extension TimeInterval { + var seconds: Int { + return Int(self.rounded()) + } + + var milliseconds: Int { + return Int(self * 1_000) + } + + var nanoseconds: UInt64 { + return UInt64(self * 1_000_000_000) + } +}