Ios 用SWIFT制作合法的倒计时计时器

Ios 用SWIFT制作合法的倒计时计时器,ios,xcode,swift,Ios,Xcode,Swift,我试图在按下按钮时获得一个倒计时标签,以(小时、分钟、秒)的方式显示倒计时。我试着把我找到的两个不同的密码连接起来。以下是我所拥有的: *updated code (some psuedo code)* var timer = NSTimer() func timerResults() { let theDate = NSDate() var endTime = theDate //+ 6 hours let timeLeft = endTime - theDate

我试图在按下按钮时获得一个倒计时标签,以(小时、分钟、秒)的方式显示倒计时。我试着把我找到的两个不同的密码连接起来。以下是我所拥有的:

*updated code (some psuedo code)*

var timer = NSTimer()

func timerResults() {
    let theDate = NSDate()
    var endTime = theDate //+ 6 hours
    let timeLeft = endTime - theDate
    timeLeftLabel.text = "\(timeLeft)"
}


@IBOutlet weak var timeLeftLabel: UILabel!

@IBAction func IBbtnUpdateTap(sender: UIButton){

        timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("timerResults"), userInfo: nil, repeats: true)

    }

此外,即使应用程序未运行,我如何使倒计时积极发生?基本上,如果用户在6小时内回来,我将创建一个奖励系统。

您丢失或需要更正的项目写在下面:

var startTime: NSDate = NSDate()
var endTime: NSDate?

func viewDidLoad() {
    let clock = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "countdown", userInfo: nil, repeats: true)
    endTime = startTime.dateByAddingTimeInterval(21600)
}

func countdown() {
    printSecondsToHoursMinutesSeconds(Int(timeLeft()))
}

func timeLeft() -> Double {
    return endTime!.timeIntervalSinceNow
}
要测量应用程序未运行的时间,需要保存应用程序进入后台的时间,然后在再次打开应用程序时比较保存的时间。时间可以保存为
NSDate
。比较两个
NSDates
可以得到一个
NSTimeInterval
,即两个日期之间经过的秒数。例如:

let remainingTime = savedTime.timeIntervalSinceNow

请参阅应用程序代理中的
ApplicationIDBecomeActive:
ApplicationIdentinterBackground:
,以获取比较并将日期保存到NSUserDefaults中的位置。

我现在无法给出详细答案,但最简单的方法如下:

当用户以一定的秒数启动计时器时,计算计时器应该结束的确切日期(
end time=now+amount of seconds
)。现在,您可以在每次显示刷新时使用计算出的剩余时间更新标签(
time left=end time-Now


通过这种方式,它保证了应用程序重新启动时的时间(当然你需要用
NSUserDefaults
或其他东西保存结束日期),而且它还保证了计时器速度没有波动(
NSTimer
不能保证)

它给了我一个“自我”错误我已经在那里了。试着把那行移到
viewDidLoad:
或其他地方。我认为错误是由于行在类中的位置造成的。手动修改
secondsLeft
非常不精确。累积错误将在几分钟后可见。保存
startDate
endDate
并从当前时间动态计算
secondsLeft
要好得多。@Sulthan很好的观点。我更新了我的答案,以反映OP问题的变化。