Curtis Cowan
Curtis Cowan

Reputation: 3

Storing a variable when the app is first installed

Attempting to store the variable DateInstalled when the app is first installed, but each time the app loads this variable is overridden by the new date.

I am new to Xcode so the answer is probably obvious. I found this code below to store the variable in the user defaults but every time it seems to skip to the else statement.

var DateInstalled: NSDate {
    get {
        if let returnValue = NSUserDefaults.standardUserDefaults().objectForKey("DateInstalled") as? NSDate {     
            return returnValue
        } else {
            NSLog("Saving new Date")
            return NSDate()          // Default value
        }
    }
    set {
        NSUserDefaults.standardUserDefaults().setObject(newValue, forKey: "DateInstalled")
        NSUserDefaults.standardUserDefaults().synchronize()
    }
}

Upvotes: 0

Views: 345

Answers (2)

Leo Dabus
Leo Dabus

Reputation: 236260

first make your date optional:

var installedDate: NSDate? {
    get {
        return NSUserDefaults().objectForKey("installedDateKey") as? NSDate
    }
    set {
        NSUserDefaults().setObject(newValue, forKey: "installedDateKey")
    }
}

and inside your viewDidLoad method add a conditional to only save its value if it stills nil:

override func viewDidLoad() {
    super.viewDidLoad()
    if installedDate == nil {
        installedDate = NSDate()
        print("First run")
    } else { 
        print("Not first run")
        print(installedDate!)
    }
}

Xcode 8 • Swift 3

var installedDate: Date? {
    get {
        return UserDefaults.standard.object(forKey: "installedDateKey") as? Date
    }
    set {
        UserDefaults.standard.set(newValue, forKey: "installedDateKey")
    }
}

Upvotes: 0

Chandu kumar.Alasyam
Chandu kumar.Alasyam

Reputation: 722

Hey @Curtis Cowan try with this

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

            let firstLaunch = NSUserDefaults.standardUserDefaults().boolForKey("FirstLaunchTime")
            if firstLaunch  {
               println("Not First launch")
            }
            else {
                println("First launch")
                NSUserDefaults.standardUserDefaults().setObject(NSDate(), forKey:"FirstLaunchTime")
                 }

            return true
      }

Upvotes: 1

Related Questions