在斯威夫特的日期之间剩下几分钟

时间:2015-01-23 03:19:23

标签: swift nsdate components nsuserdefaults nstimer

我的问题是基于时间间隔

我正在获得小时和分钟(现在)我想要创建一个75分钟的计时器,但是我希望计时器能够继续工作,即使我关闭应用程序即使是多任务处理

所以我在考虑是否将时间保存为NSUserDefault值,每次打开应用程序时都会读取存储的值并重新计算

这是我的实际代码

    override func viewDidLoad() {
    super.viewDidLoad()

    var timer = NSTimer.scheduledTimerWithTimeInterval(30, target: self, selector: Selector("update"), userInfo: nil, repeats: true)
}

func update() {
    //here I should update the GUI with the remaining minutes and do a NSUserDefault check if the 75 minutes have already
}

@IBAction func save_time(sender: AnyObject) {

    let date = NSDate()
    let calendar = NSCalendar.currentCalendar()
    let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute, fromDate: date)
    var hour = components.hour
    var minutes = components.minute + 75
    if (minutes>59){
        hour += 1
        minutes -= 60
    }
    defs.setInteger(hour, forKey: "u_hora")
    defs.setInteger(minutes, forKey: "u_minutos")


}

2 个答案:

答案 0 :(得分:2)

您可以使用NSUserDefaults将它们存储为TimeInterval,您应该创建一个时间间隔扩展来根据需要格式化时间字符串:

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var strTimer: UILabel!

    var tasksManager = NSTimer()
    var endTime:NSTimeInterval = 0
    var now: NSTimeInterval {
        return NSDate().timeIntervalSinceReferenceDate
    }

    func updateTime(){
        strTimer.text = ( endTime - now ).time
    }

    override func viewDidLoad() {
        super.viewDidLoad()
        // NSUserDefaults().removeObjectForKey("endTime")
        // loads endTime if it exists otherwise assign 0 value
        endTime = NSUserDefaults().valueForKey("endTime") as? NSTimeInterval ?? 0
        // restart timer if endTime exists
        if endTime > 0 {
            tasksManager = NSTimer.scheduledTimerWithTimeInterval(1/15, target: self, selector: "updateTime", userInfo: nil, repeats:true)
        } else {
            strTimer.text = "0:01:00.00"
        }
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
    @IBAction func startTimer (sender: AnyObject) {
        // sets endTime new timeinterval to a future point in time
        // so we need to add n seconds from now
        endTime = now + 60.0    // now + n seconds
        // saves it using NSUserDefaults
        NSUserDefaults().setValue(endTime, forKey: "endTime")
        // if the timer doest exists we create one
        if !tasksManager.valid {
            tasksManager = NSTimer.scheduledTimerWithTimeInterval(1/30, target: self, selector: "updateTime", userInfo: nil, repeats:true)
            // if the timer exists we invalidate it
        } else {
            tasksManager.invalidate()
            endTime = 0
            strTimer.text = "0:01:00.00"
            NSUserDefaults().removeObjectForKey("endTime")
        }
    }

}
extension NSTimeInterval {
    var time: String {
        return String(format: "%d:%02d:%02d.%02d", Int(self/3600), Int(self/60%60), Int(self%60), Int(self*100%100))
    }
}

答案 1 :(得分:1)

您可以将NSUserDefaults保存为当前日期和时间。

 NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey: "dateKey")

您可以通过这种方式计算保存时间和当前时间之间经过的分钟数。

if let savedDate = NSUserDefaults.standardUserDefaults().objectForKey("dateKey")  as? NSDate
{
    let currentDate = NSDate()
    let distanceBetweenDates = currentDate.timeIntervalSinceDate(savedDate)
    let secondsInAnMinute = 60.0;
    let minutesElapsed = distanceBetweenDates / secondsInAnMinute;
    println(minutesElapsed)
    println(distanceBetweenDates)
}