Skip to content

Instantly share code, notes, and snippets.

@theisegeberg
Created February 9, 2022 06:59
Show Gist options
  • Save theisegeberg/c26d72aad85a0b193227fc610fd9afa8 to your computer and use it in GitHub Desktop.
Save theisegeberg/c26d72aad85a0b193227fc610fd9afa8 to your computer and use it in GitHub Desktop.
A brute force method of getting UserDefault values.
func getUserDefaultsValueFromFile<T>(forKey key:String, type:T.Type) -> T? {
guard let bundleIdentifier = Bundle.main.bundleIdentifier else {
return nil
}
guard let libraryUrl = FileManager.default.urls(for: .libraryDirectory, in: .userDomainMask).first else {
return nil
}
let userDefaultsUrl = libraryUrl.appendingPathComponent("Preferences").appendingPathComponent(bundleIdentifier).appendingPathExtension("plist")
guard FileManager.default.fileExists(atPath: userDefaultsUrl.path) else {
return nil
}
let url = URL(fileURLWithPath: userDefaultsUrl.path)
guard let userDefaults = NSDictionary(contentsOf: url) as? Dictionary<String,AnyObject> else {
return nil
}
return userDefaults[key] as? T
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment