Skip to content

Instantly share code, notes, and snippets.

@ayakix
Last active March 5, 2020 12:57
Show Gist options
  • Save ayakix/9868ac429998fd1b63d20d7adbf70780 to your computer and use it in GitHub Desktop.
Save ayakix/9868ac429998fd1b63d20d7adbf70780 to your computer and use it in GitHub Desktop.
save/load [key: value] to/from iOS keychain
save(key: "TestKey", value: "TestValue")
print(getAllKeyChainItems())
func save(key: String, value: String) -> Bool {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: key,
kSecValueData as String: value.data(using: String.Encoding.utf8, allowLossyConversion: true)!
]
SecItemDelete(query as CFDictionary)
let status: OSStatus = SecItemAdd(query as CFDictionary, nil)
return status == noErr
}
func getAllKeyChainItems() -> [String: String] {
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
kSecReturnData as String: kCFBooleanTrue,
kSecReturnAttributes as String: kCFBooleanTrue,
kSecReturnRef as String: kCFBooleanTrue,
kSecMatchLimit as String: kSecMatchLimitAll
]
var result: AnyObject?
let lastResultCode = withUnsafeMutablePointer(to: &result) {
SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0))
}
var values = [String: String]()
if lastResultCode == noErr {
let array = result as? [[String: Any]]
for item in array! {
if let key = item[kSecAttrAccount as String] as? String,
let value = item[kSecValueData as String] as? Data {
values[key] = String(data: value, encoding: .utf8)
}
}
}
return values
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment