22 Saving and Loading App Data

User Defaults System

The simplest way to save some data between runs of an app is through the UserDefaults system. Basic calls are here :

https://developer.apple.com/documentation/foundation/userdefaults

and the Mapper app has this approach built in to UserSettings.swift with a loading function and a saving function. Be sure that the loading function makes sensible decisions for initialization is it doesn’t find the values in the defaults store.

if let x = UserDefaults.standard.array(forKey: "pinLat") 
    { pinLat = x as! [Double] }

will only load the array if there was an array found. It looks like the system only supports arrays of strings and arrays of numbers, as I was unsuccessful trying to save an array of structs. That’s probably a job for CoreData.

Use the willConnectTo session: call in SceneDelegate.swift to call for loading all your settings. It will run before the app appears.

sceneDidDisconnect() in the SceneDelegate.swift file is probably a good place to run your save to defaults function just before exiting. It gets called even if you double click directly from the app and swipe it away, whereas sceneDidEnterBackground() doesn’t get called in that circumstance. It probably doesn’t hurt to call it from both.

Core Data

CoreData provides a way more complicated and way more powerful way to maintain a persistent store of data.

https://www.hackingwithswift.com/quick-start/swiftui/how-to-configure-core-data-to-work-with-swiftui

talks about how to set up a very simple data model to retrieve pairs of strings, essentially replicating the capabilities of UserDefaults. Although the Mapper app has the structure built into the app, I’m still trying to understand how it works.

Sandboxed File System

I don’t know how to work this yet

License

Icon for the Creative Commons Attribution-ShareAlike 4.0 International License

Rick's Remote and Online Teaching Notes Copyright © 2019 by Rick Sellens is licensed under a Creative Commons Attribution-ShareAlike 4.0 International License, except where otherwise noted.

Share This Book