Created
February 5, 2022 18:15
-
-
Save apple-avadhesh/d12985396ccf75ba03c9cb203f7b2479 to your computer and use it in GitHub Desktop.
UserDefaults extension to set/get UIColor array
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//MARK: UserDefaults Extension | |
extension UserDefaults { | |
func getColors(key: String) -> [UIColor]? { | |
if let data = data(forKey: key) { | |
do { | |
if let color = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as? [UIColor] { | |
return color | |
} | |
} catch { | |
print("Error") | |
} | |
} | |
return nil | |
} | |
func setColors(_ colors: [UIColor]?, forKey key: String) { | |
if let color = colors { | |
do { | |
let data = try NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: false) | |
set(data, forKey: key) | |
} catch { | |
print("Error") | |
} | |
} | |
} | |
} | |
//MARK: Usage | |
var bgColors:Array<UIColor> { | |
get { | |
return UserDefaults.standard.getColors(key: "bgColor") ?? [UIColor.gray] | |
} | |
set { | |
UserDefaults.standard.setColors(newValue, forKey: "bgColor") | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment