计时器倒计时 6 小时,当时间到达时停止,然后在按下按钮时再次开始另一个 6 小时

Timer to countdown for 6 hours and stop when time is reached and then start again for another 6 hours when button is pressed

我需要一个计时器来倒计时 6 小时。

.到达时间必须重置

。必须在按下按钮时激活。

。当应用打开或关闭时,它必须继续 运行。

我有一个日期倒数计时器和另一个倒数计时器,只有在应用程序处于活动状态时才有效。

如何制作一个计时 6 小时的计时器?

计时器倒计时日期⬇︎

var timeCount: NSDate?
var timer = Timer()

timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(countdown), userInfo: nil, repeats: true)

@objc func countdown()
{
let endTime = "08-10-2020 18:00:00"
let formatter = DateFormatter()
formatter.dateFormat = "dd-MM-yyyy HH:mm:ss"
timeCount = (formatter.date(from: endTime))! as NSDate

let currentDate = Date()
let calendar = Calendar.current

let diffDateComponents = calendar.dateComponents([.hour, .minute, .second], from: currentDate, to: timeCount! as Date)

let countdown = "\(diffDateComponents.hour ?? 0):\(diffDateComponents.minute ?? 0):\(diffDateComponents.second ?? 0)"

let hourS = diffDateComponents.hour!
let minuteS = diffDateComponents.minute!
let secondS = diffDateComponents.second!

print(countdown)

if countdown == "0:0:0"
{
   button.setTitle("PRESS", for: .normal)
   button.backgroundColor = .green
   timer.invalidate()
}
else
{
   button.setTitle("PRESS WHEN TIME RUNS OUT" + "\n\(String(format: "%02d:%02d:%02d", hourS, minuteS, secondS))", for: .normal)
   button.backgroundColor = .red
}
}

仅当应用程序处于活动状态时计时器倒计时⬇︎

var timer = Timer()
var hours = 06
var minutes = 00
var secs = 00


timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(countdown), userInfo: nil, repeats: true)

@objc func countdown()
{
    secs = secs-1
    if (secs<0)
    {
        secs = 59
        minutes=minutes-1
        if (minutes<0)
        {
            minutes = 59
            hours = hours-1
            if (hours<0)
            {
                hours = 0
                minutes = 0
                secs = 0
                
                timer.invalidate()
            }
        }
    }

var hourp: String
var minutesp: String
var secp: String
    
if(hours<10)
{
hourp = "0" + String(describing: hours)
}
else
{
hourp = String(describing: hours)
}
if(minutes<10)
{
minutesp = "0" + String(describing: minutes)
}
else
{
minutesp = String(describing: minutes)
}
if(secs<10)
{
secp = "0" + String(describing: secs)
}
else
{
secp = String(describing: secs)
}
let timing = hourp + ":" + minutesp + ":" + secp
    
print(timing)

if hours == 0 && minutes == 0 && secs == 0
{
button.setTitle("PRESS", for: .normal)
button.backgroundColor = .green
else
{
button.setTitle("PRESS WHEN TIME RUNS OUT" + "\n\(timing)" , for: .normal)
button.backgroundColor = .red
}

}

您可以在按下按钮时获取时间并保存,然后您可以在 viewdiload 中获取时间并进行比较

是这样的;

首先创建 2 个变量,一个用于当前时间,另一个用于比较

var currentTime = Date()
var compareTime = Date().addingTimeInterval(21600) //6 hours is 21600 second

现在我们需要保存点击按钮的时间;

UserDefaults.standard.set(currentTime, forKey: "time")

现在我们需要比较这些时间;

override func viewDidLoad() {
    super.viewDidLoad()
    var time = UserDefaults.standard.object(forKey: "time")
        if let newTime = time as? Date {
        if let difference = Calendar.current.dateComponents([.hour], from: newTime, to: compareTime).hour {
            if difference > 6 {
              //make whatever you want if 6 hours is finish
            }
               }
            }
    }

这就是我最终必须做的事情,它才能按预期为我工作。

感谢@Burak Köse 的回答指导我正确的方向。

import UIKit
import Foundation

var timer = Timer()
var currentTime = Date()
var compareTime = Date().addingTimeInterval(-21600)


func setupButtonTitle()
{
 if UserDefaults.standard.object(forKey: "count6") == nil
    {
        button.setTitle("PRESS", for: .normal)
        button.backgroundColor = .green
    }
    else
    {
        button.setTitle("PRESS" + "\nIN " + "\(startTimer()))" , for: .normal)
    }
  button.addTarget(self, action: #selector(buttonTap), for: .touchUpInside)
}


func startTimer()
{
  timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(sixHourCountdown), userInfo: nil, repeats: true)
}

@objc func sixHourCountdown()
{
    let timeStarted = UserDefaults.standard.object(forKey: "count6")
    
    let timeStart = timeStarted as! Date
    let diffComponents = Calendar.current.dateComponents([.hour, .minute, .second], from: compareTime, to: timeStart)
    let hour = diffComponents.hour!
    let minute = diffComponents.minute!
    let second = diffComponents.second!
    let timeRemaining = String(format: "%02d:%02d:%02d", hour, minute, second)

    compareTime += 1
    
    if hour == 0 && minute == 0 && second == 0 || timeStart < compareTime
    {
        button.setTitle("PRESS", for: .normal)
        button.backgroundColor = .green
        timer.invalidate()
    }
    else
    {
        button.setTitle("PRESS IN" + "\n\(timeRemaining)", for: .normal)
    }
}


@objc func buttonTap()
{
    if button.currentTitle != "PRESS"
    {
        button.backgroundColor = .red
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute:
        {
         button.backgroundColor = .yellow
        })
    }
    if button.currentTitle == "PRESS" && button.backgroundColor == .green
    {
        UserDefaults.standard.set(currentTime, forKey: "count6")

        let otherVC = OTHERVC()
        self.navigationController?.pushViewController(otherVC, animated: true)
    }
}


override func viewDidLoad() {
    super.viewDidLoad()


setupButtonTitle()