Leighton Leighton - 2 months ago 13
Swift Question

How to get date and time to show a clock in UILabel

I'm new to swift (and programming in general) and right now I'm working on a project that I'd like to display a clock in a label.

right now I have this in my model:

class CurrentDateAndTime {

let currentTime = NSDateFormatter.localizedStringFromDate(NSDate(), dateStyle: .MediumStyle, timeStyle: .MediumStyle)
}


and then call it into the label with this code in my view controller:

@IBOutlet weak var currentTimeLabel: UILabel!

let currentTime = CurrentDateAndTime()



override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.

currentTimeLabel.text = currentTime.currentTime
}


The problem is this doesn't update on a second interval to show the actual time. And eventually I will be needing to get a difference between two time stamps so that I can log hours between a "start time" and a "stop time". Is this even the best/simplest way of doing it? Any clues toward my objective will be much appreciated.

Answer

Use NSTimer to schedule the callbacks at your desired interval -- in this case,

  • call tick() on self every second
  • tick() fetches the current time string and updates the UILabel

    class MyViewController {
        @IBOutlet weak var currentTimeLabel: UILabel!
    
        var timer = NSTimer()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            // Do any additional setup after loading the view, typically from a nib.
    
            timer = NSTimer.scheduledTimerWithTimeInterval(1.0
                                                                target: self,
                                                              selector: #selector(tick),    
                                                              userInfo: nil, 
                                                               repeats: true)
        }
    
        @objc func tick() {
            currentTimeLabel.text = NSDateFormatter.localizedStringFromDate(NSDate(),
                                                                            dateStyle: .MediumStyle,
                                                                            timeStyle: .MediumStyle)
        }
    }