I'm currently working on a iOS app developed in Swift and I need to store some user-created content on the device but I can't seem to find a simple and quick way to store/receive the users content on the device.
Could someone explain how to store and access local storage?
The idea is to store the data when the user executes an action and receive it when the app starts.
The simplest solution for storing a few strings or common types is UserDefaults.
The UserDefaults class provides convenience methods for accessing common types such as floats, doubles, integers, Boolean values, and URLs.
UserDefaults lets us store objects against a key of our choice, It's a good idea to store these keys somewhere accessible so we can reuse them.
Keys
struct DefaultsKeys {
static let keyOne = "firstStringKey"
static let keyTwo = "secondStringKey"
}
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
In Swift 2.0 UserDefaults was called NSUserDefaults and the setters and getters were named slightly differently:
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 config you should consider using a more robust persistent store:
CoreData
Realm
SQLite
They Say Use NSUserDefaults
When I was implementing long term (after app close) data storage for the first time, everything I read online pointed me towards NSUserDefaults. However, I wanted to store a dictionary and, although possible, it was proving to be a pain. I spent hours trying to get type-errors to go away.
NSUserDefaults is Also Limited in Function
Further reading revealed how the read/write of NSUserDefaults really forces the app to read/write everything or nothing, all at once, so it isn't efficient. Then I learned that retrieving an array isn't straight forward. I realized that if you're storing more than a few strings or booleans, NSUserDefaults really isn't ideal.
It's also not scalable. If you're learning how to code, learn the scalable way. Only use NSUserDefaults for storing simple strings or booleans related to preferences. Store arrays and other data using Core Data, it's not as hard as they say. Just start small.
Update: Also, if you add Apple Watch support, there's another potential consideration. Your app's NSUserDefaults is now automatically sent to the Watch Extension.
Using Core Data
So I ignored the warnings about Core Data being a more difficult solution and started reading. Within three hours I had it working. I had my table array being saved in Core Data and reloading the data upon opening the app back up! The tutorial code was easy enough to adapt and I was able to have it store both title and detail arrays with only a little extra experimenting.
So for anyone reading this post who's struggling with NSUserDefault type issues or whose need is more than storing strings, consider spending an hour or two playing with core data.
Here's the tutorial I read:
http://www.raywenderlich.com/85578/first-core-data-app-using-swift
If you didn't check "Core Data"
If you didn't check "Core Data"when you created your app, you can add it after 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 Delete from Core Data Lists
Delete Data from Coredata Swift
Okey so thanks to #bploat and the link to http://www.codingexplorer.com/nsuserdefaults-a-swift-introduction/
I've 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've summarized it here http://ridewing.se/blog/save-local-data-in-swift/
Using NSCoding and NSKeyedArchiver is another great option for data that's too complex for NSUserDefaults, but for which CoreData would be overkill. It also gives you the opportunity to manage the file structure more explicitly, which is great if you want to use encryption.
For Swift 4.0, this got easier:
let defaults = UserDefaults.standard
//Set
defaults.set(passwordTextField.text, forKey: "Password")
//Get
let myPassword = defaults.string(forKey: "Password")
Swift 5+
None of the answers really cover in detail the default built in local storage capabilities. It can do far more than just strings.
You have the following options straight from the apple documentation for 'getting' data from the defaults.
func object(forKey: String) -> Any?
//Returns the object associated with the specified key.
func url(forKey: String) -> URL?
//Returns the URL associated with the specified key.
func array(forKey: String) -> [Any]?
//Returns the array associated with the specified key.
func dictionary(forKey: String) -> [String : Any]?
//Returns the dictionary object associated with the specified key.
func string(forKey: String) -> String?
//Returns the string associated with the specified key.
func stringArray(forKey: String) -> [String]?
//Returns the array of strings associated with the specified key.
func data(forKey: String) -> Data?
//Returns the data object associated with the specified key.
func bool(forKey: String) -> Bool
//Returns the Boolean value associated with the specified key.
func integer(forKey: String) -> Int
//Returns the integer value associated with the specified key.
func float(forKey: String) -> Float
//Returns the float value associated with the specified key.
func double(forKey: String) -> Double
//Returns the double value associated with the specified key.
func dictionaryRepresentation() -> [String : Any]
//Returns a dictionary that contains a union of all key-value pairs in the domains in the search list.
Here are the options for 'setting'
func set(Any?, forKey: String)
//Sets the value of the specified default key.
func set(Float, forKey: String)
//Sets the value of the specified default key to the specified float value.
func set(Double, forKey: String)
//Sets the value of the specified default key to the double value.
func set(Int, forKey: String)
//Sets the value of the specified default key to the specified integer value.
func set(Bool, forKey: String)
//Sets the value of the specified default key to the specified Boolean value.
func set(URL?, forKey: String)
//Sets the value of the specified default key to the specified URL.
If are storing things like preferences and not a large data set these are perfectly fine options.
Double Example:
Setting:
let defaults = UserDefaults.standard
var someDouble:Double = 0.5
defaults.set(someDouble, forKey: "someDouble")
Getting:
let defaults = UserDefaults.standard
var someDouble:Double = 0.0
someDouble = defaults.double(forKey: "someDouble")
What is interesting about one of the getters is dictionaryRepresentation, this handy getter will take all your data types regardless what they are and put them into a nice dictionary that you can access by it's string name and give the correct corresponding data type when you ask for it back since it's of type 'any'.
You can store your own classes and objects also using the func set(Any?, forKey: String) and func object(forKey: String) -> Any? setter and getter accordingly.
Hope this clarifies more the power of the UserDefaults class for storing local data.
On the note of how much you should store and how often, Hardy_Germany gave a good answer on that on this post, here is a quote from it
As many already mentioned: I'm not aware of any SIZE limitation
(except physical memory) to store data in a .plist (e.g.
UserDefaults). So it's not a question of HOW MUCH.
The real question should be HOW OFTEN you write new / changed
values... And this is related to the battery drain this writes will
cause.
IOS has no chance to avoid a physical write to "disk" if a single
value changed, just to keep data integrity. Regarding UserDefaults
this cause the whole file rewritten to disk.
This powers up the "disk" and keep it powered up for a longer time and
prevent IOS to go to low power state.
Something else to note as mentioned by user Mohammad Reza Farahani from this post is the asynchronous and synchronous nature of userDefaults.
When you set a default value, it’s changed synchronously within your
process, and asynchronously to persistent storage and other processes.
For example if you save and quickly close the program you may notice it does not save the results, this is because it's persisting asynchronously. You might not notice this all the time so if you plan on saving before quitting the program you may want to account for this by giving it some time to finish.
Maybe someone has some nice solutions for this they can share in the comments?
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 }
For Swift 3
UserDefaults.standard.setValue(token, forKey: "user_auth_token")
print("\(UserDefaults.standard.value(forKey: "user_auth_token")!)")
For someone who'd not prefer to handle UserDefaults for some reasons, there's another option - NSKeyedArchiver & NSKeyedUnarchiver. It helps save objects into a file using archiver, and load archived file to original 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've write an simple utility to save/load objects in local storage, used sample codes above. You might want to see this.
https://github.com/DragonCherry/LocalStorage
NsUserDefaults saves only small variable sizes.
If you want to save many objects you can use CoreData as a native solution, or I created a library that helps you save objects as easy as .save() function. It’s based on SQLite.
SundeedQLite
Check it out and tell me your comments
This gives a great explanation for how to do this in Swift 5: https://www.hackingwithswift.com/example-code/system/how-to-save-user-settings-using-userdefaults
Summary:
To set a value:
let defaults = UserDefaults.standard
defaults.set("value", forKey: "key")
To get a String value:
let key = defaults.object(forKey: "StringKey") as? [String] ?? [String]()
To get integer value:
let key = defaults.integer(forKey: "IntegerKey")
I found this answer and it enabled me to save data, but since Swift 4.1 there has been a much easier way to do this using appstorage.
#AppStorage("studentNames") var studentName: String = "Put name here"
Each item must be unique, but using String you can store a large variety of data in here.
I've made a video tutorial to help you do this: http://youtube.com/watch?v=nLsJD6yL9Ps
Related
I'm learning application development working on a quiz game. I'd like to add statistics to the game. For example, the average score since the app has been downloaded. How can I store the scores on the device in order to reuse them after the app has been closed?
You should take a look at UserDefault. It's basically a dictionary that persists until the user uninstalls your app. I like to write a wrapper around it to get strong typing and ease of reference:
struct Preferences {
static func registerDefaults() {
UserDefaults.standard.register(defaults: [kAverageScore: 0])
}
// Define your key as a constant so you don't have to repeat a string literal everywhere
private static let kAverageScore = "averageScore"
static var averageScore: Double {
get { return UserDefaults.standard.double(forKey: kAverageScore) }
set { UserDefaults.standard.set(newValue, forKey: kAverageScore) }
}
}
Here's how to use it: before you call it for the first time in your app, you must register the defaults. These are the values that your app ships with. On iOS, it only really matters for the very first time the user launches your app. On OS X, do this every time your app starts because the user can delete the app's preferences from ~/Library/Application Support.
// You usually do this in viewDidLoad
Preferences.registerDefaults()
From then on, getting and setting the property is easy:
let averageScore = Preferences.averageScore
Preferences.averageScore = 5.5
You should take a look at UserDefaults
Example
let defaults = UserDefaults.standard
defaults.set(25, forKey: "Age")
defaults.set(true, forKey: "UseTouchID")
defaults.set(Double.pi, forKey: "Pi")
To read values back
let age = defaults.integer(forKey: "Age")
let useTouchID = defaults.bool(forKey: "UseTouchID")
let pi = defaults.double(forKey: "Pi")
UserDefaults
I am new in software and I have a question.
I have LoginPage called LoginVC(screenshot as below).When the user opened the app first time, if the member login with his username and password or via Facebook account, next time he opened the app he will pass the login screen and show the "NewsVC" directly. If he logged out, he will see the Login Page again.
According to my investigations I must use UserDefault method and create a local database(for example SQLite). Probably it creates a access token for the entered users. But I don't know how I will do. Maybe there is the question about this problem in this site but because of I don't know in a detailed manner couldn't find the topic.
Can you explain this topic and share an example with a simple Swift 3 code.
Thanks in advance
LoginVC ScreenShot
Securitywise, it is considered a bad practice to store login tokens in UserDefaults, I'd suggest using Keychain API instead.
"Hackers" can relatively easy read data from UserDefaults and use your access token.
Keychain API is a bit hard to use, I'd suggest trying a 3rd party library, here is one example:
https://github.com/jrendel/SwiftKeychainWrapper
More info about securing your data on iOS:
https://github.com/felixgr/secure-ios-app-dev
If you are just learning - it is OK to use UserDefaults, but once you consider moving your app to production - refactor it to Keychain.
Try following Helper method
Set User ID
func setCurrentLoginID(_ struserid: String) {
UserDefaults.standard.set(struserid, forKey:"userID")
}
Check User Login or Not
func isUserLoggedIN() -> Bool {
let str = UserDefaults.standard.object(forKey: "userID") as! String
return str.characters.count > 0 ? true : false
}
Get User ID
func loggedUserId() -> String {
let str = UserDefaults.standard.object(forKey: "userID") as? String
return str == nil ? "" : str!
}
For Logout
func logout() {
UserDefaults.standard.set(nil, forKey: "userID")
}
Assuming you wanted to know how to implement this then you can store and get the value like below:-
let default = UserDefaults.standard
default.set(accessToken, forKey: "accessToken")
default.synchronized()
//Now get like this and use guard so that it will prevent your crash if value is nil.
guard let accessTokenValue = default.string(forKey: "accessToken") else {return}
print(accessTokenValue)
I wonder how many and how big strings I can save using UserDefaults.standard
Eg:
static func saveUsername(_ token: String) {
userDefaults.set(token, forKey: "username")
userDefaults.synchronize()
}
I want to save my users: username, email, address(state,city,street), first name, last name
But I am not sure how big/how many strings I can save or what kind of impact it has on my app storing many strings
I'm creating a game that uses GameCenter and I'm trying to send and retrieve data.
This is how I'm sending data: (the function 'sendData' is provided by GameCenter with GameKit)
let nick = GCHelper()
let data = NSData(contentsOfFile: "")
try! nick.match.sendData(toAllPlayers: data as! Data, with: .reliable)
'GCHelper' is a class I'm using that contains many functions for Game Center, a download is further through the questions if you're interested. I just needed to call it to access the function.
Then to retrieve data I'm attempting to use this:
nick.match(GKMatch, didReceive: Data, fromPlayer: String)
Note: I have not filled in any of the above parameters
Here is the function I'm using to retrieve the data:
public func match(_ theMatch: GKMatch, didReceive data: Data, fromPlayer playerID: String) {
if match != theMatch {
return
}
delegate?.match(theMatch, didReceiveData: data, fromPlayer: playerID)
}
The function I'm using 'match()' is apart of the GCHelper class. GCHelper allows for you to create GameCenter game easier. Here is a link in case you want to reference it: https://github.com/jackcook/GCHelper
QUESTION
Now that I've showed you all the methods, how would I use the previous method to retrieve data? One of its parameters is 'fromPlayer' and asks for the playerId(String), but how would I know what the other players playerID is? Better yet, how would I retrieve it?
If you don't think this is a good way to handle retrieving data, how could I do it better? Is there another way to do this?
Key Facts:
The game requires 2 people and data is being exchanged between these 2 people only. I need to know how to send and retrieve data amongst the 2.
Thanks for the help! If you have any questions let me know.
This is the function I'm using to retrieve the data:
open func match(_ theMatch: GKMatch, didReceive data: Data, fromPlayer playerID: String) {
}
Now, the data I'm sending is a string. So I create a variable that unarchives the data and sets it to string format.
let myString = NSKeyedUnarchiver.unarchiveObject(with: data) as! String
After this, I need a way to get that string from the view controller or game center file to my game scene. In which I simply just stored the data using UserDefaults.
let user = UserDefaults.standard
user.set(myString, forKey: "myString")
Then in my SKScene I created a timer, in which it checks every couple of seconds to see if there's a change. It stores the values so that when a new values arrives it can compare and if it is different it does something with it, for example: update player points.
Note: This is what I found to work, someone else may have a better way, but it works fine for me.
So, I want to create my own mini social network. In registration page I have following lines of code:
var ns = NSUserDefaults.standardUserDefaults()
let array: [String] = ["\(login!)","\(password!)","\(nameSurname!)", "team", "university"] //team, university
ns.setObject(array, forKey: "\(login)")
I just create array and set it to NSUserDefaults.
And also I have page where users can change informations or datas about them, change their password for example. In this page i have following lines of code:
let login = loginTextField.text!
let password = passwordTextField.text!
let nameSurname = nameSurnameTextField.text!
let team = teamTextField.text!
let university = universityTextField.text!
let ns = NSUserDefaults.standardUserDefaults()
let array: [String] = ["\(login)","\(password)","\(nameSurname)", "\(team)", "\(university)"] //team, university course
ns.setObject(array, forKey: "\(login)")
Here I create new array and set this new array to KEY-Login. But my datas in NSUserDefaults doesn't change. How I can fix it? What I should do? Thanks)
Not sure what the issue is here. Firstly change this:
var ns = NSUserDefaults.standardUserDefaults()
//No need for " quotation marks you are using String vars
let array: [String] = [login!, password!, nameSurname!, team, university]
ns.setObject(array, forKey: "login")
//Save the changes
ns.synchronize()
//Now when we want to load the information
let ns = NSUserDefaults.standardUserDefaults()
let array = ns.objectForKey("login")
//This prints the users password
print(array![1])
//Make some changes
let newArray = ["new name", password!, nameSurname!, team, university]
ns.setObject(newArray, forKey: "login")
//Remember to save
ns.synchronize()
Maks sure you are using ns.synchronize().
Taken from the document about the Performance Tradeoffs in NSUserDefaults:
Reading from NSUserDefaults is extremely fast. It will cache values to
avoid reading from the disk, and takes about 0.5 microseconds to do
[[NSUserDefaults standardUserDefaults] boolForKey:] on a 2012 MacBook
Pro. It’s generally unnecessary (and even undesirable since it
prevents picking up new values) to cache the result of reading from
preferences.
However, writing to NSUserDefaults is a bit slower. In general, expect
it to take roughly as long as using NSPropertyListSerialization to
convert your key and value to plist data, plus a few 10s of
microseconds. For this reason, as well as memory usage, it’s generally
best to store relatively small data in CFPreferences.
Long story short, do not use synchronize in iOS 8 and later.