Created
September 28, 2022 08:06
-
-
Save ra9r/8b865ac009bf393ae5b8d2cbc36e1c36 to your computer and use it in GitHub Desktop.
A property wrapper for Keychain storage
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
| import SwiftUI | |
| import KeychainAccess | |
| @propertyWrapper | |
| struct KeychainStorage<T: Codable>: DynamicProperty { | |
| typealias Value = T | |
| let key: String | |
| @State private var value: Value? | |
| init(wrappedValue: Value? = nil, _ key: String) { | |
| self.key = key | |
| var initialValue = wrappedValue | |
| do { | |
| try Keychain().get(key) { | |
| attributes in | |
| if let attributes = attributes, let data = attributes.data { | |
| do { | |
| let decoded = try JSONDecoder().decode(Value.self, from: data) | |
| initialValue = decoded | |
| } catch let error { | |
| fatalError("\(error)") | |
| } | |
| } | |
| } | |
| } | |
| catch let error { | |
| fatalError("\(error)") | |
| } | |
| self._value = State<Value?>(initialValue: initialValue) | |
| } | |
| var wrappedValue: Value? { | |
| get { value } | |
| nonmutating set { | |
| value = newValue | |
| do { | |
| if (value == nil) { | |
| Keychain()[key] = nil | |
| } else { | |
| let encoded = try JSONEncoder().encode(value) | |
| try Keychain().set(encoded, key: key) | |
| } | |
| } catch let error { | |
| fatalError("\(error)") | |
| } | |
| } | |
| var projectedValue: Binding<Value?> { | |
| Binding(get: { wrappedValue }, set: { wrappedValue = $0 }) | |
| } | |
| } |
Author
Could you give us a example on how to use it on view ?
Also can you confirm , Does it notice the change and update the view ?
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Instead of writing the code myself, which is pretty complicated, I’ve used a Swift package called KeychainAccess. Create a blank SwiftUI project in Xcode and go to File > Swift Packages > Add Package Dependency. Paste the KeychainAccess GitHub URL and click “Next” to import. Once the package has been added, you will be able to interact with the keychain by using the Keychain class.