如何根据状态栏中的设备更新时间?

时间:2018-10-22 10:42:46

标签: ios swift datetime

所以我有以HH:mm格式显示时间的标签。并且该标签将每隔一分钟定期更新。我实际上可以通过使用timer来做到这一点,如下面的代码

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")
    }

}

,但它与状态栏中显示的时间不完全相同,会有一些秒差,如何更新始终与状态栏中显示的时间相同的时间标签?因此,如果状态栏中的时间发生变化,那么标签也会发生完全相同的变化

1 个答案:

答案 0 :(得分:0)

您可以使用Timer(fireAt:)初始化程序并传递下一个偶数分钟作为开始时间,请注意,使用此初始化程序时,您需要为RunLoop的主.commonModes添加计时器并确保在设置计时器时添加了标签的初始时间:

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: .commonModes)
    // Swift 4.2
    //  RunLoop.main.add(timer, forMode: .common)
}