how to update time as per the time from device in status bar?

偶尔善良 提交于 2021-02-05 09:16:08

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!