gpt4 book ai didi

ios - 当设备时间改变时执行函数

转载 作者:行者123 更新时间:2023-11-30 10:52:50 25 4
gpt4 key购买 nike

我试图在设备时钟改变时执行一个函数。该函数将返回学生的下一门类(class),所有类(class)都在一个数组中。

如果我理解正确的话,当设备时钟改变时我们无法执行函数。我读过一些主题,人们说要执行 60 秒或其他的计时器,但如果用户在 08:05:07 启动应用程序,则 func 将在 7 秒后执行。我想使用 do while,但我认为它会大量使用 CPU,因此也会消耗电池。没有?

有人有想法吗?

最佳答案

如果您只是说您想在未来某个特定的 Date 触发计时器,您应该只计算从现在到那时之间的时间量(使用 timeIntervalSince >),然后使用它。

例如,当前为“2019-01-20 17:11:59 +0000”,但如果我希望它在 17:15 触发,你可以这样做:

weak var timer: Timer?

func startTimer() {
let futureDate = ISO8601DateFormatter().date(from: "2019-01-20T17:15:00Z")!
let elapsed = futureDate.timeIntervalSince(Date()) // will be roughly 180.56 in this example at this moment of time

timer?.invalidate() // invalidate prior timer, if any

timer = Timer.scheduledTimer(withTimeInterval: elapsed, repeats: false) { [weak self] _ in
// whatever you want to do at 17:15
}
}

显然,无论如何,您提出的 futureDate 在您的情况下都会有所不同,但它说明了这个想法。只需计算 future 目标日期与现在之间耗时,并将其用于计时器。

现在,如果您真的担心时钟的变化,在 iOS 中您可能会观察到 significantTimeChangeNotification ,例如,

NotificationCenter.default.addObserver(forName: UIApplication.significantTimeChangeNotification, object: nil, queue: .main) { [weak self] _ in
// do something, maybe `invalidate` existing timer and create new one
self?.startTimer()
}
<小时/>

I thought to use a do while but I think it will use the CPU a lot and so the battery too. no ?

是的,循环旋转,等待一段时间过去,总是一个坏主意。一般来说,您只需设置一个计时器即可。

This func will return the next course of a student, all the courses are in a array.

这就引出了一个问题:应用程序是否会在前台运行。如果您想在将来的某个时间通知用户,无论他们现在是否正在运行应用程序,请考虑“user notifications ”。例如,请求通知权限:

UNUserNotificationCenter.current().requestAuthorization(options: [.alert, .badge, .sound]) { granted, _ in
if !granted {
// warn the user that they won't be notified after the user leaves the app unless they grant permission for notifications
DispatchQueue.main.async {
let alert = UIAlertController(title: nil, message: "We need permission to notify you of your class", preferredStyle: .alert)
if let url = URL(string: UIApplication.openSettingsURLString) {
alert.addAction(UIAlertAction(title: "Settings", style: .default) { _ in
UIApplication.shared.open(url)
})
}
alert.addAction(UIAlertAction(title: "Cancel", style: .default))
self.present(alert, animated: true)
}
}
}

然后,假设已授予权限,则安排通知:

let content = UNMutableNotificationContent()
content.title = "ClassTime"
content.body = "Time to go to math class"

let components = Calendar.current.dateComponents([.year, .month, .day, .hour, .minute], from: futureDate)
let trigger = UNCalendarNotificationTrigger(dateMatching: components, repeats: false)
let request = UNNotificationRequest(identifier: "Math 101", content: content, trigger: trigger)
UNUserNotificationCenter.current().add(request)

关于ios - 当设备时间改变时执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54277989/

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