Skip to content

Instantly share code, notes, and snippets.

@KanshuYokoo
Created March 28, 2019 18:05
Show Gist options
  • Save KanshuYokoo/4e9ac7568f808472c7a52aafea461731 to your computer and use it in GitHub Desktop.
Save KanshuYokoo/4e9ac7568f808472c7a52aafea461731 to your computer and use it in GitHub Desktop.
ios swift keyChainMabager for GenericPassword
class KeyChainManager {
static func saveGenericPassword(service:String, account:String, password:String) -> Void {
let account = userNameTextField.text
let passwordUtf8 = password.data(using: String.Encoding.utf8)!
let addquery: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: account!,
kSecAttrService as String: service ,
kSecValueData as String: passwordUtf8!]
let status = SecItemAdd(addquery as CFDictionary, nil)
guard status == errSecSuccess else {
os_log("%{public}@", type: .debug, "Error saving to keychain \(status)")
return
}
os_log("%{public}@", type: .debug, "success saving to keychain \(status)")
}
static func retrieveGenericPassword(service:String, account:String, password:String) -> String {
let user = account
let getquery: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
kSecAttrAccount as String: user!,
kSecAttrService as String: service,
kSecMatchLimit as String: kSecMatchLimitOne,
kSecReturnAttributes as String: true,
kSecReturnData as String: true]
var item: CFTypeRef?
let status = SecItemCopyMatching(getquery as CFDictionary, &item)
guard status != errSecItemNotFound else {
os_log("%{public}@", type: .debug, "Error: \(KeychainError.noPassword)")
return
}
guard status == errSecSuccess else {
os_log("%{public}@", type: .debug, "unhandledError: \(KeychainError.unhandledError(status: status))")
return
}
guard let existingItem = item as? [String : Any],
let passwordData = existingItem[kSecValueData as String] as? Data,
let password = String(data: passwordData, encoding: String.Encoding.utf8),
let accountRetrieved = existingItem[kSecAttrAccount as String] as? String
else {
os_log("%{public}@", type: .debug, "unexpectedPasswordData: \(KeychainError.unexpectedPasswordData)")
return
}
return password
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment