简体   繁体   中英

Get minutes remaining between dates in Swift

My question is based on a time interval

I'm getting the hour and minutes (NOW) and I want to create a timer for 75 minutes since that moment but I want the timer to continue working even if i close the app even on multitasking

So i was thinking if I save the time as a NSUserDefault value and every time I open the app It reads the stored value and recalculates

This is my actual code

    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")


}

You can just store them as TimeInterval using NSUserDefaults and you should create a time interval extension to format your time string as desired:

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))
    }
}

You can save the current date and time in NSUserDefaults like this.

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

You can calculate the number of minutes elapsed between saved time and current time in this way.

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)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM