Created
October 2, 2015 09:44
-
-
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
This file contains 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
// | |
// 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