gpt4 book ai didi

ios - 时间改变时如何执行操作Swift 3

转载 作者:可可西里 更新时间:2023-11-01 01:25:34 25 4
gpt4 key购买 nike

我的应用程序应该在时间改变时(每分钟,而不是每秒)执行一个操作。我实现这一目标的方法是创建一个 Timer 对象,如下所示:

var timer = Timer.scheduledTimer(timeInterval: 60, target: self, selector: #selector(ViewController.update), userInfo: nil, repeats: true)

虽然这种方式可行,但看起来不是很专业,因为应用程序不会在时间更改时准确执行更新,而是取决于对象创建的精确时刻。例如,如果 Timer 对象是在 10:10:30 创建的,那么更新只会在分钟更改后 30 秒执行。

有什么方法可以让我知道手机上时间的分钟变化?

提前致谢!

最佳答案

您可以安排第一个计时器在特定时间开火,该时间可能是下一轮分钟。这是一个示例(复制并粘贴到 Playground ):

import PlaygroundSupport
import Foundation

let cal = NSCalendar.current

var comps = cal.dateComponents([.era, .year, .month, .day, .hour, .minute], from: Date())
comps.minute = comps.minute! + 1

let nextMinute = cal.date(from: comps)

let timer = Timer(fire: nextMinute!, interval: 60, repeats: true) { _ in
print("Minute change")
}

RunLoop.current.add(timer, forMode: .defaultRunLoopMode)

PlaygroundPage.current.needsIndefiniteExecution = true

请注意,如果应用程序在后台运行,计时器将不会触发。

关于ios - 时间改变时如何执行操作Swift 3,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41757523/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com