Ios 当设备时间更改时执行func

Ios 当设备时间更改时执行func,ios,swift,time,timer,Ios,Swift,Time,Timer,当设备时钟改变时,我正在尝试执行func。 此func将返回学生的下一门课程,所有课程都在一个数组中 如果我理解正确,当设备时钟改变时,我们无法执行func。 我读过一些主题,其中有人说要执行60秒或其他计时器,但如果用户启动应用程序时是08:05:07,func将在7秒后执行。 我想用一段时间,但我认为它会使用大量的CPU和电池。没有 有人有主意吗?如果你只是说你想在未来某个特定的日期启动计时器,你应该计算从现在到那时的时间量(使用timeintervalnces),然后使用它 例如,它当前为

当设备时钟改变时,我正在尝试执行func。 此func将返回学生的下一门课程,所有课程都在一个数组中

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


有人有主意吗?

如果你只是说你想在未来某个特定的日期启动计时器,你应该计算从现在到那时的时间量(使用
timeintervalnces
),然后使用它

例如,它当前为“2019-01-20 17:11:59+0000”,但如果我希望它在17:15发射,您可以执行以下操作:

弱var定时器:定时器?
func startTimer(){
让futureDate=ISO8601DateFormatter().日期(从:“2019-01-20T17:15:00Z”)!
let eloperate=futureDate.timeIntervalSince(Date())//此时在本例中大约为180.56
计时器?.invalidate()//使前一个计时器失效(如果有)
timer=timer.scheduledTimer(withTimeInterval:Appead,repeats:false){[weak self]\uuIn
//17点15分你想做什么
}
}
很明显,您提出的
futureDate
在您的情况下会有所不同,但它说明了这个想法。只需计算未来目标日期和现在之间经过的时间,并将其用作计时器

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

NotificationCenter.default.addObserver(forName:UIApplication.significtTimeChangeNotification,对象:nil,队列:.main){[weak self]\uin
//做点什么,也许“使”现有计时器无效,然后创建一个新的计时器
self?.startTimer()
}

我想用一段时间,但我认为它会使用大量的CPU和电池。不是吗

是的,在一个循环中旋转,等待一段时间过去,总是一个坏主意。通常你只需要设置一个计时器

此func将返回学生的下一门课程,所有课程都在一个数组中

这就引出了这个应用程序是否会在前景中运行的问题。如果你想在将来某个时间通知用户,他们现在是否正在运行应用程序,请考虑“”。例如,请求通知许可:

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)
然后,假设已授予权限,则计划通知:

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)
是我干的

    private var secondesActuelles : Int = 0
    private var timer = Timer()

    private func récuperLesSecondes(date : Date) -> Int {
        let date = date
        let calendar = Calendar.current
        let second = calendar.component(.second, from: date)
        return second
    }


    override func viewDidLoad() {
        super.viewDidLoad()

        secondesActuelles = récuperLesSecondes(date: Date())

        timer = Timer.scheduledTimer(withTimeInterval: TimeInterval(60 - secondesActuelles), repeats: false, block: { (timer) in
            print("l'heure a changé")
            self.secondesActuelles = self.récuperLesSecondes(date: Date())
            print("secondesActuelles : \(self.secondesActuelles)")

        })
}
它只工作一次。但在时间间隔之后,不会改变