Skip to content

Instantly share code, notes, and snippets.

@younata
Created March 19, 2024 00:41
Show Gist options
  • Save younata/1069914cbf47c69aebaa779d53a56746 to your computer and use it in GitHub Desktop.
Save younata/1069914cbf47c69aebaa779d53a56746 to your computer and use it in GitHub Desktop.
BackgroundExecutorTestApp
import SwiftUI
import Dispatch
// A simple app to verify https://mastodon.social/@calicoding/112118821467209266
// Allows you to check using Swift Tasks, or Dispatch Queues.
//
// I found this to not be the case, but maybe this isn't realistic?
// When compiled on Xcode 15.3 (either debug or release) and run on iOS 17.4,
// background QoS tasks are still executed even when Low Power Mode is enabled.
@main
struct BackgroundExecutorApp: App {
var body: some Scene {
WindowGroup {
VStack {
Text("Low Power Mode: \(ProcessInfo.processInfo.isLowPowerModeEnabled)") // Yes, this won't automatically update.
TaskExecutor()
Divider()
DispatchExecutor()
Spacer()
}
.padding()
}
}
}
enum TaskState: Sendable {
case notRunning
case queued
case finished
var text: String {
switch self {
case .notRunning: "Not Running"
case .queued: "Queued"
case .finished: "Finished"
}
}
}
@MainActor
struct TaskExecutor: View {
@State var state: TaskState = .notRunning
var body: some View {
VStack {
Text("Using Swift Task")
HStack {
Text(verbatim: state.text)
Button("Run") {
state = .queued
Task.detached(priority: .background) {
print("Running in background swift task")
await MainActor.run {
state = .finished
}
}
}.disabled(state == .queued)
}
}
}
}
@MainActor
struct DispatchExecutor: View {
@State var state: TaskState = .notRunning
var body: some View {
VStack {
Text("Using DispatchQueue")
HStack {
Text(verbatim: state.text)
Button("Run") {
state = .queued
DispatchQueue.global(qos: .background).async {
print("Running in background dispatch queue")
DispatchQueue.main.async {
state = .finished
}
}
}.disabled(state == .queued)
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment