问题
so I have label that display time in HH:mm format. and that label will be updated periodically in every one minute. I can do that actually by using timer like the code below
class HomeVC: UIViewController {
@IBOutlet var timeLabel: UILabel!
private var timer = Timer()
private var timeBase = Date()
override func viewDidLoad() {
super.viewDidLoad()
setTime()
}
}
extension HomeVC {
//MARK: - Method related to time
func setTime() {
activateTimer()
timeLabel.text = dateTimeService.convert(date: timeBase, toFormat: "HH:mm")
dayLabel.text = dateTimeService.convert(date: timeBase, toFormat: "EEEE")
dateLabel.text = dateTimeService.convert(date: timeBase, toFormat: "d MMMM yyyy")
}
func activateTimer() {
timer = Timer.scheduledTimer(timeInterval: 60 , target: self, selector: #selector(HomeVC.updateTimer), userInfo: nil, repeats: true)
}
@objc func updateTimer() {
// add one minute
timeBase = dateTimeService.addMinuteTo(date: timeBase, minute: 1)
// update label
timeLabel.text = dateTimeService.convert(date: timeBase, toFormat: "HH:mm")
}
}
but it will not exactly the same as the time displayed in the status bar, it will have some seconds difference, how to update the label of time that will always the same as the time displayed in status bar ? so if the time in status bar change, then the label will also change exactly the same
回答1:
You can use Timer(fireAt:)initializer and pass the next even minute date as the start time, note that when using this initializer you need to add the timer to the main RunLoop for .common modes and make sure you add the initial time the label when setting up your timer:
func activateTimer() {
let now = Date()
let date = Calendar.current.date(bySettingHour: Calendar.current.component(.hour, from: now),
minute: Calendar.current.component(.minute, from: now) + 1,
second: 0,
of: now)!
timer = Timer(fireAt: date, interval: 60, target: self, selector: #selector(updateTimer), userInfo: nil, repeats: true)
RunLoop.main.add(timer, forMode: .common)
}
来源:https://stackoverflow.com/questions/52927427/how-to-update-time-as-per-the-time-from-device-in-status-bar