Atharva Vaidya Atharva Vaidya - 6 months ago 19
Swift Question

How to retrieve and assign a NSDate object from NSUserDefaults?

I am building a stopwatch application and I need to store the start date before the user closes the application and need to retrieve it when the user opens the application again.

So for example if the user starts the stopwatch and then closes the application and then after some time opens the application again the app should add the time between the opening and closing to the running time if the stopwatch was running.

I have created two functions in my viewcontroller that handle this. Here's the code:

override func viewWillAppear(animated: Bool)
{

let startTimedefault:NSUserDefaults = NSUserDefaults.standardUserDefaults()

let startTimesaved:NSDate = startTimedefault.objectForKey("start time") // This line is buggy


if(launchBool == true)
{



timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "fireStopWatch", userInfo: nil, repeats: true)

startTime = startTimesaved
}
if(launchBool == false)
{

timer.invalidate()

}

}

override func viewWillDisappear(animated: Bool)
{


NSUserDefaults.standardUserDefaults().setObject(launchBool, forKey: "Start/Stop")
NSUserDefaults.standardUserDefaults().setObject(startTime, forKey: "start time")
NSUserDefaults.standardUserDefaults().setObject(elapsedTime, forKey: "elapsed time")

}


I have gone through a couple of posts here on StackOverflow :

What's the optimum way of storing an NSDate in NSUserDefaults?

iOS - Not able to store NSDate into NSUserDefaults

Answer

Set your date object as follows:

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

Retrieve it using:

NSUserDefaults.standardUserDefaults().objectForKey("yourKey") as! NSDate