User_Defaults

User Defaults

To print the path where the plist file is stored in the iOS simulator.

let library_path = NSSearchPathForDirectoriesInDomains(.libraryDirectory, .userDomainMask, true)[0]

print("library path is \(library_path)")

Persisting data

SO

Swift guide

Custom dictionary

Specify which part of data would be under a certain class name / struct.

NSHomeDirectory()

https://crystalminds.medium.com/where-are-the-standard-userdefaults-stored-d02bf74854ff

Note about User Defaults drawbacks.
https://www.hackingwithswift.com/guide/ios-swiftui/4/2/key-points

Keys

Good way to define keys in order to access them whenever needed.

enum Keys {
	static let isLoggedIn = "AppName.State.isLoggedIn"
	static let colorScheme = "AppName.Pref.colorScheme"
}

Manager

class UserDefaultsManager {
	private let defaults = UserDefaults.standard
    
    // Singleton
    static var shared: UserDefaultsManager = UserDefaultsManager()
    private init() { }
    
    // MARK: - Public methods
    func get(key: UserDefaultsKey) -> String? {
        guard let returnedValue = defaults.object(forKey: key.rawValue) as? String else { return nil }
        return returnedValue
    }

    func set(key: UserDefaultsKey, value: String) {
        defaults.set(value, forKey: key.rawValue)
    }