Adding Items to and Querying the iOS Keychain with Swift Adding Items to and Querying the iOS Keychain with Swift ios ios

Adding Items to and Querying the iOS Keychain with Swift


In order to get this to work, you will need to retrieve the retained values of the keychain constants and store then first like so:

let kSecClassValue = kSecClass.takeRetainedValue() as NSStringlet kSecAttrAccountValue = kSecAttrAccount.takeRetainedValue() as NSStringlet kSecValueDataValue = kSecValueData.takeRetainedValue() as NSStringlet kSecClassGenericPasswordValue = kSecClassGenericPassword.takeRetainedValue() as NSStringlet kSecAttrServiceValue = kSecAttrService.takeRetainedValue() as NSStringlet kSecMatchLimitValue = kSecMatchLimit.takeRetainedValue() as NSStringlet kSecReturnDataValue = kSecReturnData.takeRetainedValue() as NSStringlet kSecMatchLimitOneValue = kSecMatchLimitOne.takeRetainedValue() as NSString

You can then reference the values in the NSMutableDictionary like so:

var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userAccount, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])

I wrote a blog post about it at:http://rshelby.com/2014/08/using-swift-to-save-and-query-ios-keychain-in-xcode-beta-4/

Hope this helps!

rshelby


I wrote a demo app and helper functions for this simple task: writing/reading a text string for a given key in Keychain.

https://github.com/marketplacer/keychain-swift

let keychain = KeychainSwift()keychain.set("hello world", forKey: "my key")keychain.get("my key")keychain.delete("my key")


My interpretation on how to add, get, delete passwords (for those who are lazy to use libraries presented in this thread):

// Saving password associated with the login and servicelet userAccount = "user's login"let service = "service name"let passwordData: NSData = self.textfield_password.text!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!let keychainQuery: [NSString: NSObject] = [        kSecClass: kSecClassGenericPassword,        kSecAttrAccount: userAccount,        kSecAttrService: service,        kSecValueData: passwordData]    SecItemDelete(keychainQuery as CFDictionaryRef) //Deletes the item just in case it already existslet keychain_save_status: OSStatus = SecItemAdd(keychainQuery as CFDictionaryRef, nil)print("Keychain saving code is: \(keychain_save_status)")...// Getting the password associated with the login and servicelet userAccount = "user's login"let service = "service name"let keychainQuery: [NSString: NSObject] = [    kSecClass: kSecClassGenericPassword,    kSecAttrService: service,    kSecAttrAccount: userAccount,    kSecReturnData: kCFBooleanTrue,    kSecMatchLimit: kSecMatchLimitOne]var rawResult: AnyObject?let keychain_get_status: OSStatus = SecItemCopyMatching(keychainQuery, &rawResult)print("Keychain getting code is: \(keychain_get_status)")if (keychain_get_status == errSecSuccess) {    let retrievedData = rawResult as? NSData    let pass = NSString(data: retrievedData!, encoding: NSUTF8StringEncoding)    print("Username: \(userAccount), password: \(pass!)")    // Do your work with the retrieved password here} else {    print("No login data found in Keychain.")...//Deleting user's credentials from Keychain. Password is optional for the query when you delete, in most cases you won't know it after all.let userAccount = "user's login"let service = "service name"let keychainQuery: [NSString: NSObject] = [        kSecClass: kSecClassGenericPassword,        kSecAttrAccount: userAccount,        kSecAttrService: service]let keychain_delete_status: OSStatus = SecItemDelete(keychainQuery as CFDictionaryRef)print("Keychain deleting code is: \(keychain_delete_status)")

The result codes and other useful info can be found in the official documentation: https://developer.apple.com/library/ios/documentation/Security/Reference/keychainservices/