Skip to content

Instantly share code, notes, and snippets.

@mhomol
Created September 17, 2015 13:21
Show Gist options
  • Save mhomol/ecb66d10b53b7ad795ef to your computer and use it in GitHub Desktop.
Save mhomol/ecb66d10b53b7ad795ef to your computer and use it in GitHub Desktop.
Bag Labs Post - Keychain and Swift -
func load(service: NSString, userName:String) -> NSString?
{
//Create the query keychain
var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userName, kCFBooleanTrue, kSecMatchLimitOneValue], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecReturnDataValue, kSecMatchLimitValue])
var dataTypeRef :Unmanaged<AnyObject>?
// Search for the keychain items
let status: OSStatus = SecItemCopyMatching(keychainQuery, &dataTypeRef)
let opaque = dataTypeRef?.toOpaque()
var contentsOfKeychain: NSString?
if let op = opaque
{
let retrievedData = Unmanaged<NSData>.fromOpaque(op).takeUnretainedValue()
// Convert the data retrieved from the keychain into a string
contentsOfKeychain = NSString(data: retrievedData, encoding: NSUTF8StringEncoding)
}
else
{
println("Nothing was retrieved from the keychain. Status code \(status)")
}
return contentsOfKeychain
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment