Search code examples
iosswiftuserdefaultsswiftyuserdefaults

UserDefaults not saving when used in a framework


I have a framework that needs to save values locally, for that I chose UserDefaults.

However, the values are never saved, and the following read function always return "" after restarting the app

class Preferences {
    let preferences : UserDefaults

    init (preferences : UserDefaults) {
        self.preferences = preferences
    }

    // Private Key
    func savePrivateKey(key : String) {
        writeString(value: key, key: privateKeyKey)
    }

    func readPrivateKey() -> String! {
        return readString(key: privateKeyKey)
    }

    private func readString(key : String) -> String? {
        if preferences.object(forKey: key) == nil {
            return "bananas"
        } else {
            return preferences.string(forKey: key)
        }
    }

    private func writeString(value : String, key : String) {
        preferences.set(value, forKey: key)
    }

    fileprivate let privateKeyKey = "privateKey"
}

Initialized with:

let preferences = Preferences(preferences: UserDefaults.standard)

I have tried:

  • Simulator and physical Device
  • Debug and Release
  • UserDefaults and SwiftyUserDefaults

The strange thing is that this is saving the Bool values, but not the string ones.

I thought that this might be from not using correctly UserDefaults, but SwiftyUserDefaults gets the same result.


Solution

  • import Foundation
    
    public class AppDefaults {
        private let defaultStringKey = "DefaultString"
    }
    
    public extension AppDefaults {
    
        var defaultString: String? {
            get { return UserDefaults.standard.string(forKey: defaultStringKey) }
            set { UserDefaults.standard.set(newValue?.description, forKey: defaultStringKey) }
        }
    
    }
    

    I suggest you make a separate file called something like AppDefaults etc. You can then access each default as such

    var text = AppDefaults().defaultString
    

    You can then overwrite it and it will save automatically using

    AppDefaults().defaultString = "Bananas"