Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save variable after my app closes (swift)

I'm trying to save a variable in Xcode so that it saves even after the app has closed, how ever when I access it I do it from a several different classes and files, and I change the value of the variable when I access it. Therefore similar threads do not completely apply, the value to be stored is a string and here is the code I have up until now:

var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(Token, forKey: "") as! String

I believe this is the correct format, but I don't know how to call it to change it because when I try I get an error message saying expected declaration.

Anyway any help would be very much appreciated.

like image 567
lucas rodriguez Avatar asked Aug 10 '15 15:08

lucas rodriguez


3 Answers

First of all you have to specify an unique key to store the variable (in the example MyKey ).

In AppDelegate > applicationDidFinishLaunching register the key with a default value.
The benefit is you can use a non-optional variable and you have a defined default value.

let defaults = UserDefaults.standard
let defaultValue = ["MyKey" : ""]
defaults.register(defaults: defaultValue)

Now you can from everywhere read the value for the key

let defaults = UserDefaults.standard
let token = defaults.string(forKey: "MyKey")

and save it

let defaults = UserDefaults.standard
defaults.set(token, forKey: "MyKey")
like image 162
vadian Avatar answered Nov 18 '22 03:11

vadian


Swift 3

(thanks to vadian's answer)

In AppDelegate > applicationDidFinishLaunching :

    let defaults = UserDefaults.standard
    let defaultValue = ["myKey" : ""]
    defaults.register(defaults: defaultValue)

to save a key:

let defaults = UserDefaults.standard
defaults.set("someVariableOrString", forKey: "myKey")
defaults.synchronize()

to read a key:

    let defaults = UserDefaults.standard
    let token = defaults.string(forKey: "myKey")
like image 21
Test Avatar answered Nov 18 '22 02:11

Test


Let's say you have a string variable called token

To save/update the stored value on the device:

NSUserDefaults.standardUserDefaults().setObject(token, forKey: "mytoken")
NSUserDefaults.standardUserDefaults().synchronize()

In the code above I made sure to give the key a value ("mytoken"). This is so that we later can find it.

To read the stored value from the device:

let token = NSUserDefaults.standardUserDefaults().objectForKey("mytoken") as? String

Since the method objectForKey returns an optional AnyObject, I'll make sure to cast it to an optional String (optional meaning that it's either nil or has a value).

like image 4
Mattias Avatar answered Nov 18 '22 01:11

Mattias