Skip to content

Instantly share code, notes, and snippets.

@pardel
Created October 2, 2015 09:44
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pardel/be30bbbb31c6cf624d5d to your computer and use it in GitHub Desktop.
Save pardel/be30bbbb31c6cf624d5d to your computer and use it in GitHub Desktop.
An example of using Latch (https://github.com/DanielTomlinson/Latch) to store user credentials
//
// MyAppAccount
//
struct MyAppAccount {
let latch = Latch(service: (NSBundle.mainBundle().bundleIdentifier ?? "com.example.MyApp"))
var username: String? {
get { return getValueForKey("username") }
set(newObject) { setValueForKey("username", value: newObject) }
}
var password: String? {
get { return getValueForKey("password") }
set(newObject) { setValueForKey("password", value: newObject) }
}
private func getValueForKey(key: String) -> String? {
guard let data = latch.dataForKey(key), let value = NSString(data: data, encoding: NSUTF8StringEncoding) else {
return nil
}
return value as String
}
private func setValueForKey(key: String, value: String?) {
if let value = value where value.characters.count > 0, let data = value.dataUsingEncoding(NSUTF8StringEncoding) {
latch.setObject(data, forKey: key)
} else {
latch.removeObjectForKey(key)
}
}
}
// Store
var account = MyAppAccount()
account.username = "email@example.com"
account.password = "password"
// Retrieve
var account2 = MyAppAccount()
account2.username
account2.password
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment