Timer Not Updating – Solution | Hacking Swift 5.5, Xcode 13, and iOS 15

https://www.youtube.com/watch?v=Xi_uBYKigAA

Timer Not Working in SwiftUI Error – Fixed

by Alexandra Kropova from Mammoth Interactive

Did you build a timer with no error messages, but for some reason the timer refuses to count down? Read the solution in this post.

Want to learn more? Enroll in Complete Web & App Development with Machine Learning For All (125 Hours). Free in the Mammoth Unlimited Membership. Get 250+ courses and 2,000 hours at a dirt-cheap price.

An example where the problem occurs:

struct ContentView: View { 
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
       
    @State var timerAmount = 10
    var body: some View { 
                
 
              Text(timerAmount )
                     .onReceive(timer) { _ in
                          
                               timerAmount -= 1
             }  
     }
} 

Solution

To make the timer update, the solution is to put the Text element (or whichever element is dependent on the timer) into a Stack, such as a VStack, HStack or ZStack element. Use use the following Swift 5.5 code:

struct ContentView: View { 
    let timer = Timer.publish(every: 1, on: .main, in: .common).autoconnect()
       
    @State var timerAmount = 10
    var body: some View { 
                 
         VStack {
              Text(timerAmount )
                     .onReceive(timer) { _ in
                          
                               timerAmount -= 1
             }  
         }
     }
} 

Toolkit:

  • Xcode 13
  • Swift 5.5
  • SwiftUI 3
  • iOS 15

 

Suggest more solutions or ask a question in the comments below.

Want to learn more? Enroll in Complete Web & App Development with Machine Learning For All (125 Hours). Free in the Mammoth Unlimited Membership. Get 250+ courses and 2,000 hours at a dirt-cheap price.
Mammoth Interactive Favicon

Why you NEED to take this course :

Get in Touch.

Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.

EMAIL US

support@mammothinteractive.com