Home > Back-end >  Need help updating the time on my app, it is static
Need help updating the time on my app, it is static

Time:05-28

I am coding a app for school, and have a welcome page with the "hello it is currently xx;xx. I have the time updating, but I cant figure a way out to make it constantly refresh, as I test the build, it only updates once. here is my code

func getCurrentTime() -> String {

  let formatter = DateFormatter()

  formatter.timeStyle = .short


  let dateString = formatter.string(from: Date())
    
  return dateString
}

CodePudding user response:

Currently what you're doing is only grabbing the time once, so the solution is to constantly run your function. To do this we can use an infinite while loop, generally you'd have a condition that might break the loop but in the case of time we can just have a condition that will never evaluate to false, so true. This will allow the returned value to always be correct however I'm assuming that some other function is calling getCurrentTime() rather than getCurrentTime setting the value that's displayed thus you would have to set that value inside the while loop, kind of like this.

while true {
    timeToDisplay = getCurrentTime()
} 

CodePudding user response:

As mentioned above, you are grabbing the date at a point in time. You need a mechanism to repeatedly obtain the date and update the UI when it changes. The simplest way to do this is with a timer.

To minimise load you should only update the UI when the time changes. The snippet below updates every minute, but you can take the same approach with seconds.

let df = DateFormatter() //you should create it as a static property on your object as it has a heavyweight init
df.timeStyle = .short

var lastMinutes = 0
var cal = Calendar.current

let timer = Timer.scheduledTimer(withTimeInterval: 0.51, repeats: true) { _ in
    let date = Date()
    let minutes = cal.component(.minute, from: date)
    guard minutes != lastMinutes else {return}
    lastMinutes = minutes
    timeTextField.text = df.string(from: date) // update your text field
}
timer.fire()

CodePudding user response:

I don't have any syntax about the Swift. But the algorithm is similar any language. In Javascript you can use setInterval function. I have search a little Swift alternatives of setInterval and found this.

var timer = Timer.scheduledTimer(timeInterval: 1000.0, target: self, selector: #selector(fireTimer), userInfo: nil, repeats: true)

}

#objc func fireTimer(){
    //var hour = getHours()
    //var minute = getMinutes()
    //var second = getSeconds()
    //return hour   ":"   minute   ":"   second
    //or print somewhere to show the clock
}
  • Related