Skip to content

Instantly share code, notes, and snippets.

@mhomol
Created September 17, 2015 13:20
Show Gist options
  • Select an option

  • Save mhomol/a7be3e88f142d96e0ea5 to your computer and use it in GitHub Desktop.

Select an option

Save mhomol/a7be3e88f142d96e0ea5 to your computer and use it in GitHub Desktop.
Bag Labs Post - Keychain and Swift - SaveLogin
//Don't forget to add the Security.framework to your project.
import Security
private let kSecClassValue = NSString(format: kSecClass)
private let kSecAttrAccountValue = NSString(format: kSecAttrAccount)
private let kSecValueDataValue = NSString(format: kSecValueData)
private let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword)
private let kSecAttrServiceValue = NSString(format: kSecAttrService)
private let kSecMatchLimitValue = NSString(format: kSecMatchLimit)
private let kSecReturnDataValue = NSString(format: kSecReturnData)
private let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne)
func saveLogin(password: NSData, userName:String, service:String)
{
//Create the query
var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userName, password], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue])
// Delete any existing items
SecItemDelete(keychainQuery as CFDictionaryRef)
//Add the query to the keychain
var status: OSStatus = SecItemAdd(keychainQuery as CFDictionaryRef, nil)
//Verify the status and handle your error, status of 0 means everything worked
println(status)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment