How to save local data in a Swift application?

I am currently working on an iOS application developed in Swift, and I need to save some user-generated content on the device, but I cannot find a simple and quick way to store / retrieve user content on the device.

Can someone explain how to store and access local storage?

The idea is to store data when the user performs an action and receives it when the application starts.

+130
ios swift nsuserdefaults
Feb 20 '15 at 11:46
source share
9 answers

The easiest solution, if you just store two lines, is NSUserDefaults , in Swift 3 this class was renamed simply UserDefaults .

It's best to store your keys somewhere globally so you can use them elsewhere in your code.

 struct defaultsKeys { static let keyOne = "firstStringKey" static let keyTwo = "secondStringKey" } 

Swift 3.0, 4.0 and 5.0

 // Setting let defaults = UserDefaults.standard defaults.set("Some String Value", forKey: defaultsKeys.keyOne) defaults.set("Another String Value", forKey: defaultsKeys.keyTwo) // Getting let defaults = UserDefaults.standard if let stringOne = defaults.string(forKey: defaultsKeys.keyOne) { print(stringOne) // Some String Value } if let stringTwo = defaults.string(forKey: defaultsKeys.keyTwo) { print(stringTwo) // Another String Value } 

Swift 2.0

 // Setting let defaults = NSUserDefaults.standardUserDefaults() defaults.setObject("Some String Value", forKey: defaultsKeys.keyOne) defaults.setObject("Another String Value", forKey: defaultsKeys.keyTwo) // Getting let defaults = NSUserDefaults.standardUserDefaults() if let stringOne = defaults.stringForKey(defaultsKeys.keyOne) { print(stringOne) // Some String Value } if let stringTwo = defaults.stringForKey(defaultsKeys.keyTwo) { print(stringTwo) // Another String Value } 

For anything more serious than minor configurations, flags, or base strings, you should use some kind of persistent storage. Realm is currently a popular option , but you can also use SQLite or Apple with their own CoreData .

+183
Feb 20 '15 at 12:15
source share

They say they use NSUserDefaults

When I first introduced the long-term (after closing the application) data warehouse, everything I read on the Internet pointed to NSUserDefaults. However, I wanted to keep the dictionary, and although it was possible, it was painful. I spent hours trying to make errors like disappear.

NSUserDefaults is also limited in function

Further reading showed how reading / writing NSUserDefaults really makes the application read / write all or nothing, all at once, so it is not efficient. Then I found out that getting an array is not so simple. I realized that if you store more than a few lines or booleans, NSUserDefaults is actually not perfect.

It also does not scale. If you are learning to program, learn a scalable way. Use only NSUserDefaults to store simple strings or logical values ​​associated with settings. Storing arrays and other data using Core Data is not as difficult as they say. Just start small.

Update: Also, if you add support for Apple Watch, there is another potential factor. Your NSUserDefaults application is now automatically sent to the Watch extension.

Using master data

So I ignored the warnings that Core Data is a more complex solution, and started reading. Three hours later, it worked for me. I had an array of tables stored in Core Data and reloading data when opening the application! The textbook code was quite simple to adapt, and I was able to save both the headers and the detailed arrays in it, only experimenting a little.

Therefore, for those who read this post, who are faced with problems like NSUserDefault or need something more than storing strings, consider spending an hour or two playing with the master data.

Here is a tutorial that I read:

http://www.raywenderlich.com/85578/first-core-data-app-using-swift

If you did not check "Master Data"

If you did not check “Baseline” when creating the application, you can add it later, and it only takes five minutes:

http://craig24.com/2014/12/how-to-add-core-data-to-an-existing-swift-project-in-xcode/

http://blog.zeityer.com/post/119012600864/adding-core-data-to-an-existing-swift-project

How to remove from master data lists

Delete data from Coredata Swift

+50
Aug 06 '15 at 2:28
source share

Ok thanks to @bploat and the link to http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/

I found that the answer is quite simple for some basic string storage.

 let defaults = NSUserDefaults.standardUserDefaults() // Store defaults.setObject("theGreatestName", forKey: "username") // Receive if let name = defaults.stringForKey("username") { print(name) // Will output "theGreatestName" } 

I summarized it here http://ridewing.se/blog/save-local-data-in-swift/

+11
Feb 20 '15 at 12:15
source share

Using NSCoding and NSKeyedArchiver is another great option for data that is too complex for NSUserDefaults , but for which CoreData would be redundant. It also gives you the ability to more clearly manage the file structure, which is great if you want to use encryption.

+8
Aug 09 '15 at 19:44
source share

For Swift 4.0, this has become easier:

 let defaults = UserDefaults.standard //Set defaults.set(passwordTextField.text, forKey: "Password") //Get let myPassword = defaults.string(forKey: "Password") 
+7
July 22 '18 at 13:22
source share

Swift 3.0

Setter: local storage

 let authtoken = "12345" // Userdefaults helps to store session data locally let defaults = UserDefaults.standard defaults.set(authtoken, forKey: "authtoken") defaults.synchronize() 

Getter: local storage

  if UserDefaults.standard.string(forKey: "authtoken") != nil { //perform your task on success } 
+6
Jan 30 '17 at 6:44
source share

For Swift 3

 UserDefaults.standard.setValue(token, forKey: "user_auth_token") print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)") 
+5
Oct 26 '16 at 6:42 on
source share

For those who do not prefer to handle UserDefaults for some reason, there is another option - NSKeyedArchiver and NSKeyedUnarchiver. It helps to save objects to a file using the archiver and load archive files into source objects.

 // To archive object, let mutableData: NSMutableData = NSMutableData() let archiver: NSKeyedArchiver = NSKeyedArchiver(forWritingWith: mutableData) archiver.encode(object, forKey: key) archiver.finishEncoding() return mutableData.write(toFile: path, atomically: true) // To unarchive objects, if let data = try? Data(contentsOf: URL(fileURLWithPath: path)) { let unarchiver = NSKeyedUnarchiver(forReadingWith: data) let object = unarchiver.decodeObject(forKey: key) } 

I wrote a simple utility for saving / loading objects in local storage, which were used in the examples above. You might want to see this. https://github.com/DragonCherry/LocalStorage

+4
Jun 03 '17 at 3:36 on
source share

Set the value in the keyPrice key: UserDefaults.standard.set ("2" forKey: "keyPrice")

Get stored value: let getPrice = UserDefaults.standard.string (forKey: "keyPrice")

0
Feb 05 '19 at 17:02
source share



All Articles