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

标签 ios swift datetime

我的应用程序应该在时间发生变化时执行操作(每分钟,而不是每秒)。我实现此目的的方法是创建一个 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/

相关文章:

ios - 键盘完成键 Action swift iOS 不起作用

ios - 后台获取 NSPersistentCloudKitContainer 变化设置通知

swift - RxSwift+Alamofire 自定义映射器错误处理

Python:给定 UTC 中的当前时间,您如何确定特定时区中一天的开始和结束时间?

sql - 如果日期不与现有日期重叠,则将日期范围更新到日期列中

iphone - 如何让 UIWebView 加载网页,但 URL 在 UILabel 上?

ios - UIButton 约束失败,但适用于 UILabel

iphone - 将文本字段的文本保留在模态视图 Controller 中

ios - 使用 DateFormatter 在 Swift 中显示 future 日期而不是过去日期

mysql ORDER BY datetime 类型字段未按预期排序