Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to synchronise my UILabel with the system time?

Tags:

time

ios

swift

I have a label in which I want to show the system time. And I want my label to be synchronized with it i.e. the label will always show the same time as the time shown in the status bar.

I set the text of the label to the system time using this snippet:

let date = NSDate()
let formatter = NSDateFormatter()
formatter.dateFormat = "hh:mm"
label.text = formatter.stringFromDate(date)

But I don't know when to run this code. I thought I can run it every minute, but that doesn't always work. Consider this:

The user starts the app at system time 08:00:30, the above code is run. The time shown in the status bar and the time shown in my label are the same: 08:00

At system time 08:01:00, the time shown in the status bar changes to 08:01. But since 1 minute has not yet passed since the start of the app, the label's text is still 08:00.

That's why I said doing it every minute doesn't always work.

I also thought of using an NSTimer to run that code every second or millisecond. But isn't that too excessive and will cause performance issues?

Is there a "proper" way to do this?

like image 249
Sweeper Avatar asked Oct 18 '22 02:10

Sweeper


1 Answers

You can keep calling your function every minute as you said but at the first time you can run it after 30 seconds (system time was 08:00:30) then continue calling after 1 minute and in that case I think they will be identical

like image 155
Hossam Ghareeb Avatar answered Oct 20 '22 23:10

Hossam Ghareeb