当前时间到达特定时间时触发功能的最佳方法

时间:2018-08-09 05:45:04

标签: timer swift4.1

嘿,我想在设备时钟达到晚上6点时将应用程序的模式从白天更改为晚上,并在时钟达到早上6点时再次将其更改。现在,我每秒使用Timer来检查时间并启动我的功能。但是我觉得这不是最好的方法。

1 个答案:

答案 0 :(得分:0)

您好,您的方法不是最佳方法,因为这会消耗用户设备的电池寿命。我在项目中运用了一个技巧。您可以做一件事,在应用程序启动时,检查是否已达到“特定时间”。而且,当设备的“时区”或“时钟时间”更改时,您还需要检查它。

func checkTimeToFireMethod(){

        let calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
        let date = Date()
        calendar.locale = Locale(identifier: "en_US_POSIX")
        let hour = calendar.component(.hour, from: date)
        let minutes = calendar.component(.minute, from: date)
        let seconds = calendar.component(.second, from: date)
        let timeNowInSeconds = seconds + minutes*60 + hour*3600
        var timeLeft = 0
        // 6 am (06:00:00) changes to seconds (6*3600) and current time in seconds. here we are checking if the current time is less than 6:00:00 am
        if timeNowInSeconds < 6*3600{
            timeLeft = 6*3600 - timeNowInSeconds
        }
        // 6 pm (18:00:00) changes to seconds (18*3600) and current time in seconds. here we are checking if the current time is between  6:00:00 am and 6:00:00 pm.
        if timeNowInSeconds < 18*3600 && timeNowInSeconds >= 6*3600{
             timeLeft = 18*3600 - timeNowInSeconds

        }
        // 6 pm (18:00:00) changes to seconds (18*3600) and current time in seconds. here we are checking if the current time is greater than  6:00:00 am and 6:00:00 pm.
        else if timeNowInSeconds >= 18*3600{
            timeLeft = 24*3600 - timeNowInSeconds
        }

        // to avoid any descripancy
        // check 30 seconds prior to actual time
        self.perform(#selector(self.myFuncation), with: nil, afterDelay: TimeInterval(timeLeft - 30))
        // check on time
        self.perform(#selector(self.myFuncation), with: nil, afterDelay: TimeInterval(timeLeft))

        // check 30 seconds after  actual time
        self.perform(#selector(self.myFuncation), with: nil, afterDelay: TimeInterval(timeLeft + 30))
    }

然后调用您的函数来执行任务

func myFuncation(){
} 

还添加以下通知:-

     NotificationCenter.default.addObserver(self, selector: #selector(self.checkTimeToFireMethod), name: NSNotification.Name.NSSystemClockDidChange, object: nil)
   NotificationCenter.default.addObserver(self, selector: #selector(self.checkTimeToFireMethod), name: NSNotification.Name.NSSystemTimeZoneDidChange, object: nil)