Skip to content

Instantly share code, notes, and snippets.

@ra9r
Created September 28, 2022 08:06
Show Gist options
  • Select an option

  • Save ra9r/8b865ac009bf393ae5b8d2cbc36e1c36 to your computer and use it in GitHub Desktop.

Select an option

Save ra9r/8b865ac009bf393ae5b8d2cbc36e1c36 to your computer and use it in GitHub Desktop.
A property wrapper for Keychain storage
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 })
}
}
@ra9r
Copy link
Copy Markdown
Author

ra9r commented Sep 28, 2022

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.

@X901
Copy link
Copy Markdown

X901 commented Dec 15, 2022

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