Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 557
Atharva Vaidya Avatar asked Nov 04 '14 11:11

Atharva Vaidya


People also ask

How do I get NSUserDefaults in Objective C?

you can access NSUserDefaults in any controller (Any class of your application) of your application with the same code you have written in one class. Show activity on this post. NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults]; NSString *myString = [defaults stringForKey:@"strings"];

What is NSUserDefaults in Swift?

Overview. The NSUserDefaults class provides a programmatic interface for interacting with the defaults system. The defaults system allows an app to customize its behavior to match a user's preferences. For example, you can allow users to specify their preferred units of measurement or media playback speed.


2 Answers

Set your date object as follows:

UserDefaults.standard.set(Date(), forKey:"yourKey") 

Retrieve it using:

UserDefaults.standard.object(forKey: "yourKey") as? Date 

Date will be optional of course, because it might never have been set.

like image 75
Sujith Thankachan Avatar answered Oct 08 '22 21:10

Sujith Thankachan


Swift 3/4/5 version using Date (type alias) instead of NSDate:

let yourDate = UserDefaults.standard.object(forKey: "yourKey") as? Date UserDefaults.standard.set(yourDate, forKey: "yourKey") 

Remember to use conditional cast operator as? to avoid crash if there is no date yet under "yourKey" in UserDefaults.

like image 28
KlimczakM Avatar answered Oct 08 '22 23:10

KlimczakM