Last active
April 16, 2018 02:07
-
-
Save hongseok/1377a1ab5196a41402d30a0a475d3bc1 to your computer and use it in GitHub Desktop.
Simple Swift Keychain Sample
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
public class Keychain { | |
public class func save(val: String, key: String) { | |
let query = keychainQuery(withKey: key) | |
let objectData = val.data(using: .utf8, allowLossyConversion: false) | |
if SecItemCopyMatching(query, nil) == noErr { | |
if let dictData = objectData { | |
_ = SecItemUpdate(query, NSDictionary(dictionary: [kSecValueData: dictData])) | |
} else { | |
_ = SecItemDelete(query) | |
} | |
} else { | |
if let dictData = objectData { | |
query.setValue(dictData, forKey: kSecValueData as String) | |
_ = SecItemAdd(query, nil) | |
} | |
} | |
} | |
public class func load(key: String) -> String? { | |
let query = keychainQuery(withKey: key) | |
query.setValue(kCFBooleanTrue, forKey: kSecReturnData as String) | |
query.setValue(kCFBooleanTrue, forKey: kSecReturnAttributes as String) | |
var result: CFTypeRef? | |
let status = SecItemCopyMatching(query, &result) | |
guard | |
let resultsDict = result as? NSDictionary, | |
let resultsData = resultsDict.value(forKey: kSecValueData as String) as? Data, | |
status == noErr | |
else { | |
return nil | |
} | |
return String(data: resultsData, encoding: .utf8) | |
} | |
private class func keychainQuery(withKey key: String) -> NSMutableDictionary { | |
let result = NSMutableDictionary() | |
result.setValue(kSecClassGenericPassword, forKey: kSecClass as String) | |
result.setValue(key, forKey: kSecAttrService as String) | |
result.setValue(kSecAttrAccessibleAlwaysThisDeviceOnly, forKey: kSecAttrAccessible as String) | |
return result | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment