I want to automatically save a bunch of NSUserDefaults when the user closes the app with the home button, not when pressing a save button (which is all I have been able to find so far). What would be the best way to do this?
For example, I have a text view and two buttons which can increase and decrease the font size. Instead of saving the NSUSerDefaults for text size every time the user changes the size of the text, would it be possible to save it once when the app closes and without using a save button?
I have found this which talks about methods such as applicationWillTerminate: and applicationWillResignActive: but am not quite sure how to implement these.
I have set the pointSize to 18 by default, but when I increase that:
@IBAction func largerTextButton(sender: AnyObject) {
mainTextView.font = UIFont(name: mainTextView.font.fontName, size: mainTextView.font.pointSize+1)
println(mainTextView.font.pointSize)
}
And save it with the following:
func applicationWillResignActive(application: UIApplication) {
userDefaults.setObject(mainTextView.font.pointSize, forKey: "textSize")
userDefaults.synchronize()
}
func applicationWillTerminate(application: UIApplication) {
userDefaults.setObject(mainTextView.font.pointSize, forKey: "textSize")
userDefaults.synchronize()
}
It saves fine when I add this code to a button, but does not save under applicationWillResignActive and applicationWillTerminate so it is not an issue with the saving itself. Rather the applicationWillResignActive and applicationWillTerminate methods which I am having trouble with.
The next time I run the application I still get 18, using this to check:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
println(toString(userDefaults.objectForKey("textSize")))
...