[AltStore] Extends background fetch time until finished refreshing apps

Plays silent audio in background
This commit is contained in:
Riley Testut
2019-06-21 11:33:12 -07:00
parent 39c84e623a
commit a3ffa1795a
5 changed files with 184 additions and 64 deletions

View File

@@ -91,81 +91,90 @@ extension AppDelegate
}
}
// Wait a few seconds so we have a chance to discover nearby AltServers.
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
func finish(_ result: Result<[String: Result<InstalledApp, Error>], Error>)
BackgroundTaskManager.shared.performExtendedBackgroundTask { (taskResult, taskCompletionHandler) in
if let error = taskResult.error
{
ServerManager.shared.stopDiscovering()
print("Error starting extended background task.", error)
}
// Wait a few seconds so we have a chance to discover nearby AltServers.
DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
let content = UNMutableNotificationContent()
var shouldPresentAlert = true
do
func finish(_ result: Result<[String: Result<InstalledApp, Error>], Error>)
{
let results = try result.get()
shouldPresentAlert = !results.isEmpty
ServerManager.shared.stopDiscovering()
for (_, result) in results
let content = UNMutableNotificationContent()
var shouldPresentAlert = true
do
{
guard case let .failure(error) = result else { continue }
throw error
let results = try result.get()
shouldPresentAlert = !results.isEmpty
for (_, result) in results
{
guard case let .failure(error) = result else { continue }
throw error
}
content.title = NSLocalizedString("Refreshed all apps!", comment: "")
}
catch
{
print("Failed to refresh apps in background.", error)
content.title = NSLocalizedString("Failed to Refresh Apps", comment: "")
content.body = error.localizedDescription
shouldPresentAlert = true
}
content.title = NSLocalizedString("Refreshed all apps!", comment: "")
}
catch
{
print("Failed to refresh apps in background.", error)
content.title = NSLocalizedString("Failed to Refresh Apps", comment: "")
content.body = error.localizedDescription
shouldPresentAlert = true
}
if shouldPresentAlert
{
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print(error)
if shouldPresentAlert
{
let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 0.01, repeats: false)
let request = UNNotificationRequest(identifier: UUID().uuidString, content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request) { (error) in
if let error = error {
print(error)
}
}
}
}
switch result
{
case .failure(ConnectionError.serverNotFound): completionHandler(.newData)
case .failure: completionHandler(.failed)
case .success: completionHandler(.newData)
}
}
let group = AppManager.shared.refresh(installedApps, presentingViewController: nil)
group.beginInstallationHandler = { (installedApp) in
guard installedApp.app.identifier == App.altstoreAppID else { return }
// We're starting to install AltStore, which means the app is about to quit.
// So, we say we were successful even though we technically don't know 100% yet.
// Also since AltServer has already received the app, it can finish installing even if we're no longer running in background.
if let error = group.error
{
finish(.failure(error))
}
else
{
var results = group.results
results[installedApp.app.identifier] = .success(installedApp)
finish(.success(results))
switch result
{
case .failure(ConnectionError.serverNotFound): completionHandler(.newData)
case .failure: completionHandler(.failed)
case .success: completionHandler(.newData)
}
taskCompletionHandler()
}
let group = AppManager.shared.refresh(installedApps, presentingViewController: nil)
group.beginInstallationHandler = { (installedApp) in
guard installedApp.app.identifier == App.altstoreAppID else { return }
// We're starting to install AltStore, which means the app is about to quit.
// So, we say we were successful even though we technically don't know 100% yet.
// Also since AltServer has already received the app, it can finish installing even if we're no longer running in background.
if let error = group.error
{
finish(.failure(error))
}
else
{
var results = group.results
results[installedApp.app.identifier] = .success(installedApp)
finish(.success(results))
}
}
group.completionHandler = { (result) in
finish(result)
}
}
group.completionHandler = { (result) in
finish(result)
}
}
}

View File

@@ -0,0 +1,102 @@
//
// BackgroundTaskManager.swift
// AltStore
//
// Created by Riley Testut on 6/19/19.
// Copyright © 2019 Riley Testut. All rights reserved.
//
import AVFoundation
class BackgroundTaskManager
{
static let shared = BackgroundTaskManager()
private var isPlaying = false
private let audioEngine: AVAudioEngine
private let player: AVAudioPlayerNode
private let audioFile: AVAudioFile
private let audioEngineQueue: DispatchQueue
private init()
{
self.audioEngine = AVAudioEngine()
self.audioEngine.mainMixerNode.outputVolume = 0.0
self.player = AVAudioPlayerNode()
self.audioEngine.attach(self.player)
do
{
let audioFileURL = Bundle.main.url(forResource: "Silence", withExtension: "m4a")!
self.audioFile = try AVAudioFile(forReading: audioFileURL)
self.audioEngine.connect(self.player, to: self.audioEngine.mainMixerNode, format: self.audioFile.processingFormat)
}
catch
{
fatalError("Error. \(error)")
}
self.audioEngineQueue = DispatchQueue(label: "com.altstore.BackgroundTaskManager")
}
}
extension BackgroundTaskManager
{
func performExtendedBackgroundTask(taskHandler: @escaping ((Result<Void, Error>, @escaping () -> Void) -> Void))
{
func finish()
{
self.player.stop()
self.audioEngine.stop()
self.isPlaying = false
}
self.audioEngineQueue.async {
do
{
try AVAudioSession.sharedInstance().setCategory(.playback, options: .mixWithOthers)
try AVAudioSession.sharedInstance().setActive(true)
// Schedule audio file buffers.
self.scheduleAudioFile()
self.scheduleAudioFile()
let outputFormat = self.audioEngine.outputNode.outputFormat(forBus: 0)
self.audioEngine.connect(self.audioEngine.mainMixerNode, to: self.audioEngine.outputNode, format: outputFormat)
try self.audioEngine.start()
self.player.play()
self.isPlaying = true
taskHandler(.success(())) {
finish()
}
}
catch
{
taskHandler(.failure(error)) {
finish()
}
}
}
}
}
private extension BackgroundTaskManager
{
func scheduleAudioFile()
{
self.player.scheduleFile(self.audioFile, at: nil) {
self.audioEngineQueue.async {
guard self.isPlaying else { return }
self.scheduleAudioFile()
}
}
}
}

View File

@@ -43,6 +43,7 @@
<true/>
<key>UIBackgroundModes</key>
<array>
<string>audio</string>
<string>fetch</string>
</array>
<key>UILaunchStoryboardName</key>

Binary file not shown.