I'm trying to program a small interval timer application with Swift and am stuck on not being able to update my view probably. The view is updated only when one interval ends, so the timer gets to 0 and a new interval starts with a new time.
I thought that I wouldn't have to do much because of the ObservableObjects and the @Published declaration, but it seems I have some crucial error in my logic about swift and interaction between views and models?
I have an TimerClockView for the timer embedded in my RunningTimerView. An IntervalTimerViewModel for logic stuff and connection, though I don't think it's properly done and has space for improvement. Then my MyTimer class for the timer stuff.
Till now I tried to use different timers, timer.scheduledTimer and timer.publish to see if that makes any difference. I tried to save the new value in different variables throughout my view model and myTimer and tried to use a listener callback when counting the time, like I have for when one interval finishes (currentProcessingDuration = 0). I tried to introduce the timer at different space because I thought maybe I call another object but it doesn't seems like it. Switching between passing the viewmodel in the initialiser to adding it to EnvironmentObject and using @EnvironmentObject instead of @ObservableObject. Passing it with the view while calling navigationdestination as well ChatGPT-4 says my code is fine and the ObservableObject/ObservedObject/@Published should work like it's intended... so it may be another problem not related to the given code? or get is stupid, sometimes the case For readability I shorten my classes..
TimerClockView
struct TimerClockView: View {
@ObservedObject var viewModel: IntervalTimerViewModel
// some code
var body: some View {
ZStack {
// some code
if viewModel.isPlaying {
Text("\(viewModel.myTimer.currentProcessingDurationString)")
.font(.system(size: customSize * 0.25))
Text("\(viewModel.myTimer.getTotalInMinutes())")
.offset(y: customSize * 0.2)
.font(.system(size: customSize * 0.15))
} else {
Text("\(viewModel.myTimer.getTotalInMinutes())")
.font(.system(size: customSize * 0.25))
}
}
.foregroundStyle(currentColor)
}
}
RunningTimerView
struct RunningTimerView: View {
@ObservedObject var viewModel: IntervalTimerViewModel
// some code
var body: some View {
ZStack {
VStack {
// some code
TimerClockView(viewModel: viewModel,customSize: UIScreen.main.bounds.width * 0.8)
// some code
}
.background(currentColor)
}
}
}
IntervalTimerViewModel
class IntervalTimerViewModel: ObservableObject {
@Published var settings: Settings
@Published var intervalProfile: IntervalProfile
@Published var myTimer: MyTimer
@Published var currentInterval: Interval?
@Published var currentExercise: Exercise?
@Published var volumeLevel: Float = 50
@Published var intervalMode: IntervalMode?
@Published var currentActivityType: ActivityType = .none
@Published var isPlaying: Bool = false
var currentRound: Int = 1
var totalRounds: Int = 0
var totalExercises: Int = 0
var currentExerciseIndex: Int = 0
init(intervalProfile: IntervalProfile, settings: Settings) {
self.settings = settings
self.intervalProfile = intervalProfile
self.myTimer = MyTimer()
guard let interval = intervalProfile.intervals.first else { return }
self.currentInterval = interval
self.currentExercise = interval.exercises.first
self.totalRounds = interval.roundCounter
self.totalExercises = interval.exerciseCounter
self.intervalMode = interval.intervalMode
setCurrentTimer(interval: interval)
setTimerListener()
}
func skipToNextExercise() -> Bool {
// some code
}
func setCurrentTimer(interval: Interval?) {
if let interval = interval {
myTimer.setTimes(exercises: interval.exerciseCounter, repetition: interval.roundCounter, activityDuration: interval.activityDuration, pauseDuration : interval.pauseDuration, variableDuration: interval.variableDuration, currentProcessingDuration: interval.activityDuration, warmUpTime: settings.defaultWarmUpTime)
}
}
func setTimerListener() {
myTimer.onExercisePauseTimerEnd = { [weak self] in
self?.setNextActivity()}
}
// for when one interval ends and the next starts
func setNextActivity() {
guard let interval = currentInterval else { return}
print("\(currentActivityType)")
switch currentActivityType {
case .none:
myTimer.currentProcessingDuration = settings.defaultWarmUpTime
currentActivityType = .warmUp
break
case .activity:
if currentExerciseIndex + 1 < interval.exercises.count {
currentExerciseIndex += 1
currentExercise = interval.exercises[currentExerciseIndex]
myTimer.currentProcessingDuration = interval.pauseDuration
currentActivityType = .pause
} else {
if currentRound < totalRounds {
currentRound += 1
currentExerciseIndex = 0
currentActivityType = .roundPause
myTimer.currentProcessingDuration = interval.variableDuration
} else {
stopTimer()
return
}
}
break
case .pause:
currentExercise = interval.exercises[currentExerciseIndex]
myTimer.currentProcessingDuration = interval.activityDuration
currentActivityType = .activity
break
case .roundPause:
currentExerciseIndex = 0
currentExercise = interval.exercises[currentExerciseIndex]
myTimer.currentProcessingDuration = interval.activityDuration
currentActivityType = .activity
break
case .warmUp:
currentExerciseIndex = 0
currentExercise = interval.exercises[currentExerciseIndex]
myTimer.currentProcessingDuration = interval.activityDuration
currentActivityType = .activity
break
case .coolDown:
print("")
// not yet implemented
// Method could be used to define cooldown after sesion for stretching or whatever
break
}
startTimer()
}
func startTimer() {
if !isPlaying {
changeVolume()
myTimer.startTimer()
isPlaying = true
}
}
func pauseTimer() {
if isPlaying {
changeVolume()
myTimer.pauseTimer()
isPlaying = false
}
}
func continueTimer() {
if !isPlaying {
changeVolume()
isPlaying = true
myTimer.continueTimer()
}
}
func stopTimer() {
isPlaying = false
changeVolume()
myTimer.stopTimer()
resetActivities()
}
// some code
}
MyTimer
class MyTimer: ObservableObject {
@Published var totalDuration: Int = 0
@Published var currentProcessingDuration: Int = 0
@Published var totalDurationString: String = ""
@Published var currentProcessingDurationString: String = ""
@Published var audioPlayer: AVAudioPlayer?
private var lastCurrentProcessingDuration: Int = 0
var onExercisePauseTimerEnd: (() -> Void)?
@Published var timer: Timer?
init() {
audioPlayer = AVAudioPlayer()
audioPlayer?.volume = loadAudioVolume()
}
func setTimes(exercises: Int = 0, repetition: Int = 0, activityDuration: Int = 0, pauseDuration : Int = 0, variableDuration: Int = 0, currentProcessingDuration: Int = 0, warmUpTime: Int = 0) {
let totalActivity = exercises * activityDuration * repetition
let activityPause = exercises * pauseDuration * repetition
let roundPause = (repetition - 1) * variableDuration
self.totalDuration = totalActivity + activityPause + roundPause + warmUpTime
self.currentProcessingDuration = currentProcessingDuration
self.totalDurationString = getTotalInMinutes()
self.currentProcessingDurationString = getCurrentProcessingInMinutes()
}
func startTimer() {
configureAudioPlayer(audioName: "startIntervalSound")
timer?.invalidate()
timer = Timer.scheduledTimer(withTimeInterval: 1.0, repeats: true) {
[weak self] _ in DispatchQueue.main.async {
self?.tick()
}
}
}
func tick() {
print("currentProcessingDuration: \(currentProcessingDuration)")
print("totalDuration: \(totalDuration)")
if currentProcessingDuration == lastCurrentProcessingDuration {
configureAudioPlayer(audioName: "beepStartSound")
}else if currentProcessingDuration <= 4 && currentProcessingDuration > 0 {
configureAudioPlayer(audioName: "beepSound")
}
if currentProcessingDuration == 0 {
configureAudioPlayer(audioName: "beepEndSound")
onExercisePauseTimerEnd?()
}
if currentProcessingDuration > 0 && totalDuration > 0 {
currentProcessingDuration -= 1
totalDuration -= 1
}
if(totalDuration == 0) {
stopTimer()
return
}
}
func pauseTimer() {
configureAudioPlayer(audioName: "pauseIntervalSound")
timer?.invalidate()
}
func continueTimer() {
configureAudioPlayer(audioName: "continueIntervalSound")
lastCurrentProcessingDuration = currentProcessingDuration
startTimer()
}
func stopTimer() {
configureAudioPlayer(audioName: "stopIntervalSound")
timer?.invalidate()
timer = nil
AudioServicesPlaySystemSound(1100)
}
func getTotalInMinutes() -> String {
return getTimeInMinutes(processedTime: totalDuration)
}
func getCurrentProcessingInMinutes() -> String {
return getTimeInMinutes(processedTime: currentProcessingDuration)
}
func getTimeInMinutes(processedTime: Int) -> String {
return String(format: "%d:%02d", processedTime / 60, processedTime%60)
}
// some code
}
Could someone give me some hints for solving my problem?
Thanks to Iorem ipsum for giving the hint.
I am now passing the MyTimer as parameter into to TimerClockView and initializing it into an ObservedObject. Works like a charm
struct TimerClockView: View {
@ObservedObject var viewModel: IntervalTimerViewModel
@ObservedObject var myTimer: MyTimer
// some code
var body: some View {
ZStack {
// some code
if viewModel.isPlaying {
Text(myTimer.currentProcessingDurationString)
.font(.system(size: customSize * 0.25))
Text(myTimer.totalDurationString)
.offset(y: customSize * 0.2)
.font(.system(size: customSize * 0.15))
} else {
Text(myTimer.totalDurationString)
.font(.system(size: customSize * 0.25))
}
}
.foregroundStyle(currentColor)
}
}
struct RunningTimerView: View {
@ObservedObject var viewModel: IntervalTimerViewModel
// some code
TimerClockView(viewModel: viewModel, myTimer: viewModel.myTimer, customSize: UIScreen.main.bounds.width * 0.8)
// some code
}