Save variable in swift even when app is turned off - ios

Do you guys know how to save a var in swift, even when the app is closed.
When someone opens the app on his phone for the first time he can choose a name, what I want is, if he selected a name at the first time. He don't need to choose anymore and the name is saved even when the app is closed and turned on again.
Thanks!

Best way is to use NSUserDefaults.
With the NSUserDefaults class, you can save settings and properties related to application or user data.
ex:
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject("Foo", forKey: "name")
and then to read
if let name = defaults.stringForKey("name")
{
println(name)
}

Related

Swift 3 How to save and load data

I'm a software development student and for a school project me and a friend are making a iOS Swift game and we are learning Swift 3 as we progress in the game aspects.
Now, we have come to the part of the development where we question how is game data going to be saved (I'm talking about scores, player's name, in-game money, if the player plays in mute or unmute.. you know that kind of stuff)
The game uses an avatar and the player can customize it, so data customization needs to be saved too.
Right now we manage this data throught variables like
var eyeColor = "#04ff45"
var eyetype = 3 // And so on
I have done some research on this and found that there are various methods we could use.
Like, we could use Core Data or a Dictionary or a JSON file.
I'd like to know which could be the best/easiest way to acomplish this, if we need to use any specific libraries and some basic code on how to write/read the data
Thank you very much
Best way to save scores is by using NSUserDefaults
To save settings such as volume, you can follow the model I have below.
//When you tap on the mute button, execute this code.
if soundSwitch { //true
UserDefaults.standard.set(false, forKey: "SoundSwitch")
soundSwitch = false
} else { //false
UserDefaults.standard.set(true, forKey: "SoundSwitch")
soundSwitch = true
}
If you are saving players money, name and all this other stuff, it would be better to save them in some kind of database. I'm not sure if you can do that with GameCenter.
The easiest way to save data you are working with on the device would be to use NSUserDefaults. All you have to do is create a key, and store a value under that key. You can then use the key to access the value later and it is stored on the phone's permanent memory.
For example, you would use the user defaults to create a key called "eye color", store a value under that key, and then access it later using the term that you know the value is stored under (i.e. the key). This is a very simple way of storing such information.

How do I save a var when my iOS app closes? [duplicate]

This question already has answers here:
How to save local data in a Swift app?
(12 answers)
Closed 6 years ago.
In total I have 2 viewcontrolers. The App is the same like this guy made in a tutorial. https://www.youtube.com/watch?v=LrCqXmHenJY&t=40s
To make a start, I made a var:
import UIKit
var list = ["Task 1", "Task 2", "Task 3", "Task 4"]
class FirstViewController: UIViewController , UITableViewDelegate, UITableViewDataSource{
My current problem is, that when I close the app no ToDo's which I created were saved.
What do I need to do to save my var list so that my ToDo-List isn't empty when I open it for the next time?
You can use UserDefaults to save/load application state or configurations. For complex requirements use CoreData
Writing/Saving before app termination
let defaults = UserDefaults.standard
defaults.set(true, forKey: "Enabled")
Reading/Loading on app launch
let defaults = UserDefaults.standard
let enabled = defaults.bool(forKey: "Enabled")
Read the related Apple docs here.
If you want an easy way to store a list of strings, you can use UserDefaults. Another way to do this is to use Core Data which is more difficult to use. It is usually used to store more complex data structures than an array of strings.
To save the string array to UserDefaults, do this:
UserDefaults.standard.set(list, "myStringArray")
You can replace "myStringArray" with any key you want.
To retrieve it, do this:
list = UserDefaults.standard.stringArray(forKey: "myStringArray")
I suggest you save the array in this method in App Delegate:
func applicationDidEnterBackground(_ application: UIApplication) {
}
For more info on User Defaults, see https://developer.apple.com/reference/foundation/userdefaults
You have very simple needs. Look at NSUserDefaults (now called UserDefaults in Swift 3.)
Save your data to UserDefaults when it changes, and read it back when you display your view controller.
As Eric says in his comments, make list an instance variable of your view controller.
EDIT:
In the comments below, rmaddy pointed out that the app will be saving a to-do list. That will likely grow in complexity from an array of a handful of items to a larger array or potentially a more complex structure.
Given that, you might want to look at saving your data to a plist file in the documents directory (quite simple) or using NSCoding if you have custom objects other than the small list of "property list" types that can be saved to a plist.
Both of those solutions read and write the data all at once to a file. That might be ok for a to-do list app.
If you need to change parts of a larger data-set and leave the rest unchanged then it's time to consider a database like Core Data.

How to save entered data to make it available after app restart

I have my own custom data structures which receive input through the ViewController class. The interface is a simple text field, which is linked to a variable that the contents of the text field is copied to. Upon launching the app, the text field should be prepopulated with data entered in the past. However, as soon as I close the app, the data is lost. I am new to programming and assume this can be remedied by implementing the necessary functions in AppDelegate class, more specifically, under the default applicationWillTerminate function. If this is correct, how do I implement the data saving process? If not, where & how do I make sure data entered is stored so that fields are prepopulated the next time the app is opened?
If you need to store small amount of data, take a look at NSUserDefaults.
If your data better fits to a database, you can use SQLite (may be with a wrapper) or Core Data.
There is also a modern but not yet very mature cross-platform mobile database called Realm (partially open-sourced at the moment).
Since you are saving TextField data(which use mostly small string text) Use NSUserDefaults to store the string for persistence. What you need to do is at textFieldEndEditing save the text to NSUserDefaults and in viewDidLoad assign it to textField.
Saving To NSUserDefaults:
let defaults = NSUserDefaults.standardUserDefaults()
defaults.setObject(myTextField.text, forKey: "TextFieldText")
defaults.synchronize()
Retrieving from NSUserDefaults:
let defaults = NSUserDefaults.standardUserDefaults()
if let savedText = defaults.stringForKey("TextFieldText")
{
print("Textfield Text: \(savedText)")
}

Removing a key from NSUserDefaults not working

I have a logout function in my app. Seems to be a weird problem where it doesn't save the NSUserDefaults. Here I simply want to remove the key. However after logging out if I then open the app again it will find that this key is still in the NSUserDefaults.
func didLogout() {
// Clear user data
let settings = NSUserDefaults.standardUserDefaults()
settings.removeObjectForKey("userData")
settings.synchronize()
unregisterForRemoteNotifications()
openLoginScreen()
}
Any ideas what I could be doing wrong here?
try this
DispatchQueue.main.async {
UserDefaults.standard.removeObject(forKey: YOUR_KEY_HERE)
}
helped for me
removeObjectForKey(_:)
Removing a default has no effect on the value returned by the
objectForKey: method if the same key exists in a domain that precedes
the standard application domain in the search list.
Just use another key instead of userData. It might exists in another domain.
The code above is correct. The key will be still there, but it will return only nil value. So, when user logout you can set
NSUserDefaults.standardUserDefaults().removeObjectForKey("userData")
and when new user login you can set new value by checking
if NSUserDefaults.standardUserDefaults().objectForKey("userData") == nil
One of our (XCTest) unit tests was failing every other run. It turned out that -removeObjectForKey: was — inexplicably — only working every other run. I verified this with defaults.dictionaryRepresentation before and after -removeObjectForKey:. I thought perhaps the keys were being added to two domains and the first remove wasn't getting them both (the docs say this can happen) so I cleverly added a second remove, but that also had no effect. My solution was to set the key to the uninitialized value instead.
Any ideas?
There is no issue in your above code you might have set data in app delegate or when you login your app, or you have mistyped key value.
If you want to clear all data. This will Work
let appDomain = NSBundle.mainBundle().bundleIdentifier!
NSUserDefaults.standardUserDefaults().removePersistentDomainForName(appDomain)
I did the following to delete the userdefault of the app on user loggout
private static let userDefaults = NSUserDefaults.standardUserDefaults()
private static let userTokenKey = "userTokenKey"
userDefaults.removeObjectForKey(userTokenKey)
userDefaults.synchronize()

How to store form data in a swift app

I'm working on my first app and I need some help understanding what kind of data storage I need. I'm familiar with PHP, SQL, and databases but I don't know where to start with this project.
The app is pretty much a basic form with text fields, pickers, and uploaded images. At the end, the user will press submit and all of their data will be sent in an email.
What is the best way to store their data, so the user can go to previous screens and have their previously entered info still there. And then what is the best way to store the data after they press submit to send it in an email?,
Thanks so much for your help!
If it's just form data that you're storing once for submission, for simplicity sake, I recommend just stuffing it in a global dictionary that you can access from different views. Swift makes this easy by just adding an empty swift file and defining your dictionary at the top:
var myFormData: [String: AnyObject]()
You can now access "myFormData" form anywhere in your app, add and remove stuff from it.
You shouldn't technically need to "reload previous views" because of the way the navigation stack works. Anything you go back to should hold it's info.
If you really need to save the data to allow the user to close the app and then pick up where they left off much later, then I recommend simply kicking your dictionary to NSUserDefaults. It doesn't sound like something that needs to involve a database.
You can use a class called NSUserDefaults
var defaults: NSUserDefaults = NSUserDefaults.standardUserDefaults() //make an instance
defaults.setObject("Bob", forKey: "myName") //storing a value
defaults.synchronize() //synchronize data
println(defaults.objectForKey("myName")!) //retrieve the data

Resources