One important criteria we set out for our application was that it should be able to save the question the user is on, and store this information even through closing the app and restarting the device. When the app is reopened, it should then recall the last position when the user starts playing the game again and return them to the relevant question.
To do this, information needs to be stored in a file which is saved to the device’s storage so that it can persist when the software stops running. There are several different formats this data can take, however perhaps the simplest, most common and the one that we have chosen to use here is NSUserDefaults.
NSUserDefaults is a class in Swift which is used to store simple information so that it is persistent. It is limited in what it can store, so it is mainly used for simple data such as integers and strings. Common implementations of NSUserDefaults include saving a user’s birthday, name or other such simple information.
This approach, then, while limited is perfect for what is needed for our app. In order to save which question the user is on, in the way that our code is structured, only a single integer needs to be saved. By saving the integer value of the current question, this number can then be passed into several functions when the app is run to update the text to display the right question, and set the current index of the array of question objects. This will effectively resume the application from the last question, although in effect it simply re-sets the current question when the app loads. This is a simple implementation of persistence, however in this context it s all that is really required.
currentQuestion = defaults.integerForKey("currentLevel")
This is essentially the code to load the current question from the user defaults. This code is run when the app loads, so that if a value is stored from a previous session it is loaded into the ‘currentQuestion’ variable, which is used for updating the display and for comparing with the array index.
defaults.setObject(currentQuestion + 1, forKey: "currentLevel")
This snippet of code then sets the next question in the array to the appropriate key in the user defaults. This code is run when a user answers a question correctly, at the same time as updating the view and showing congratulations & facts.
This is a simple solution to the problem, but one that works effectively and more than adequately fits the needs of the project. As a result of incorporating this code into our app, it now saves states between sessions. This is one more requirement fulfilled.