Locksmith is a library from Matthew Palmer that really improves how we can interact with the Keychain. Let's look at the basics:
Reading Data
let dictionary = Locksmith.loadDataForUserAccount("kyloren")
Writing Data
do {
try Locksmith.saveData(
["saberColor": "#FF0000"],
forUserAccount: "kyloren"
)
} catch { }
Updating Data
do {
try Locksmith.updateData(
["saberColor": "#30FF00"],
forUserAccount: "kyloren"
)
} catch { }
Deleting Data
do {
try Locksmith.deleteDataForUserAccount("kyloren")
} catch { }
That's just the beginning though. Locksmith supports almost every feature Keychain has to offer. It also embraces protocols, and protocol extensions. Let's look at an example of how to improve our own types, making them easier to store in the Keychain.
Let's say we have a simple struct in our app to represent user accounts. We'll implement a couple of protocols from Locksmith on it:
struct JediTempleAccount: GenericPasswordSecureStorable,
CreateableSecureStorable, ReadableSecureStorable,
DeleteableSecureStorable {
let username: String, password: String
let service = "jedi-temple"
var account: String { return username }
var data: [String: AnyObject] { return ["password": password] }
}
Now we can work with accounts and the Keychain like this:
let account = JediTempleAccount(username: "kyloren", password: "yaysith")
do { try account.createInSecureStore() } catch { } // save
let result = account.readFromSecureStore() // retrieve
do { try account.deleteFromSecureStore() } catch { } // delete
More info about Locksmith can be found at git.io/locksmith