SwiftUI on macOS: Settings, defaults and About source code

This is the Swift source code to accompany the article SwiftUI on macOS: Settings, defaults and About.

TemperaDriveApp.swift

import SwiftUI

@main
struct TemperaDriveApp: App {
let theLocalTemperaDrive = TemperaDrive()
var body: some Scene {
Window(“TemperaDrive”, id: “main”) {
ContentView()
}
Settings {
SettingsView()
}
}
}

ContentView.swift

import SwiftUI

struct ContentView: View {
var body: some View {
if isInited {
VStack {
Button(“Check”) {
theTemperaDrive?.getVolumes()
}
Text((theTemperaDrive?.theVolsList.joined(separator: “n”) ?? “None”))
.font(.largeTitle)
}
.padding()
.background(.windowBackground)
} else {
VStack {
Text(“Waiting for results…”)
.font(.title)
}
.background(.gray)
}

}
}

#Preview {
ContentView()
}

SettingsView.swift

import SwiftUI

let unitsCelsius = “Celsius”
let unitsFahrenheit = “Fahrenheit”

struct SettingsView: View {

var body: some View {
TabView {
ShowView()
.tabItem {
Image(systemName: “eye”)
Text(“Show”)
}
UnitsView()
.tabItem {
Image(systemName: “thermometer.medium”)
Text(“Units”)
}
TimerView()
.tabItem {
Image(systemName: “timer”)
Text(“Timer”)
}
}
.frame(width: 400, height: 150)
}
}

struct ShowView: View {
@AppStorage(“showTemps”) var showTemps = true

var body: some View {
VStack(alignment: .leading, content: {
Toggle(“Show Temperatures and Repeat”, isOn: $showTemps)
})
}
}

struct UnitsView: View {
@AppStorage(“tempUnits”) var tempUnits = unitsCelsius

var body: some View {
Picker(“Units”, selection: $tempUnits) {
Text(“Celsius”).tag(unitsCelsius)
Text(“Fahrenheit”).tag(unitsFahrenheit)
}
.pickerStyle(.radioGroup)
}
}

struct TimerView: View {
@AppStorage(“repeatTime”) var repeatTime = 5.0

var body: some View {
List {
Slider(value: $repeatTime, in: 5305, step: 30, onEditingChanged: { print(“($0)”)
}, minimumValueLabel: Text(“5”),
maximumValueLabel: Text(“305”),
label: { Text(“Seconds”) })
Text(“Time interval = (Int(repeatTime)) seconds”)
}
}
}

#Preview {
SettingsView()
}

TemperaDrive.swift

import Foundation
import SwiftUI

var isInited = false
var theTemperaDrive: TemperaDrive?

@Observable
class TemperaDrive: NSObject {
var theVolsList = [“”]
var theTimer: Timer?
var theTimeInterval = 30.0

override init() {
super.init()
self.getVolumes()
isInited = true
theTemperaDrive = self
theTimeInterval = UserDefaults.standard.double(forKey: “repeatTime”)
if theTimeInterval < 5.0 {
theTimeInterval = 5.0
} else if theTimeInterval > 305.0 {
theTimeInterval = 305.0
}
if (UserDefaults.standard.bool(forKey: “showTemps”)) {
self.theTimer = Timer.scheduledTimer(withTimeInterval: self.theTimeInterval, repeats: true, block: { _ in
self.fireTimer()
})
}
}

@objc func fireTimer() {
self.getVolumes()
}

func getVolumes() {
self.theVolsList = [“”]
// …
}
}

End of code supplement.