I currently have a Text()
which changes based on a 10 minute timer (600 seconds
), in the format 9:59
, 9:58
etc.
The below code was working, however now I'm facing a problem. I wanted to perform an action at 540 seconds
(9:00
), so I added:
if self.countdown.secondsLeft <= 540 && !codeSent {
self.codeSent = true
}
however that gives the following error:
Modifying state during view update, this will cause undefined behavior.
So instead, I wanted to add the seconds left in my onReceive(self.countdown.secondsLeft)
method as seen below - but swift doesn't accept self.countdown.secondsLeft
as it's not a @Published
Int
:
Instance method 'onReceive(_:perform:)' requires that 'Int' conform to 'Publisher'
However, it is.
My code is below:
HomeView.swift
struct HomeView: View {
@ObservedObject var waitingCountdown = CountDown(secondsLeft: 600)
var body: some View {
ZStack {
WaitingTimer(countdown: self.waitingCountdown)
}
}
WaitingTimer.swift
struct WaitingTimer: View {
@ObservedObject var countdown: CountDown
@State var codeSent = false
var body: some View {
VStack{
Text("\(timerText())")
.font(.system(size: 28))
.fontWeight(.bold)
.foregroundColor(Color("Exit"))
.frame(width: 80, height: 40)
.padding(EdgeInsets(top: 3, leading: 10, bottom: 3, trailing: 10))
.background(
Capsule()
.fill(Color.white)
.opacity(0.7)
)
.overlay(
Capsule()
.stroke(Color("Exit"), lineWidth: 2)
)
.onReceive(self.countdown.secondsLeft){
}
.onAppear{
print("Start countdown")
self.countdown.start()
}
.onDisappear {
self.countdown.stop()
}
}.frame(minWidth: 0, maxWidth: .infinity, minHeight: 0, maxHeight: .infinity, alignment: .topLeading)
.padding(.top, 30)
.padding(.leading, 30)
}
func timerText() -> String{
print("seconds left: \(self.countdown.secondsLeft) | codeSent: \(codeSent)")
let minutes = Int( floor(Double(self.countdown.secondsLeft) / 60) )
let _seconds = (self.countdown.secondsLeft) - (minutes * 60)
if self.countdown.secondsLeft <= 540 && !codeSent {
print("SECONDS LEFT: \(self.countdown.secondsLeft) | CODESENT: \(codeSent)")
self.codeSent = true
}
// Show 9:09 instead of 9:9
let seconds = _seconds < 1 ? "0\(_seconds)" : String(_seconds)
print("Minutes \(minutes) Seconds left: \(seconds)")
return "\(minutes):\(seconds)"
}
}
CountDown.swift
class CountDown: ObservableObject {
init(secondsLeft: Int){
self.secondsLeft = secondsLeft
}
@Published var secondsLeft: Int
var timer: Timer?
func start(){
print("start timer: \(self.secondsLeft)")
self.timer = Timer.scheduledTimer(withTimeInterval: 1, repeats: true){ _ in
self.secondsLeft -= 1
}
}
func stop(){
self.timer?.invalidate()
} }
Any idea what the problem is?
@Zorgan For the require that conform to publisher bug :
Instance method 'onReceive(_:perform:)' requires that 'Int' conform to 'Publisher'
add $ on your Published property in onReceive
onReceive(self.countdown.$secondsLeft)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With