Skip to content

Commit

Permalink
Background downloading attempt fix
Browse files Browse the repository at this point in the history
  • Loading branch information
XITRIX committed Nov 18, 2024
1 parent 9268d82 commit 3ac3f23
Showing 1 changed file with 31 additions and 9 deletions.
40 changes: 31 additions & 9 deletions iTorrent/Services/BackgroundService/AudioBackgroundService.swift
Original file line number Diff line number Diff line change
Expand Up @@ -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 }
Expand Down Expand Up @@ -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
Expand All @@ -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() {
Expand All @@ -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)
}
}

0 comments on commit 3ac3f23

Please sign in to comment.