Skip to content

Instantly share code, notes, and snippets.

@chrishulbert
Last active August 29, 2015 14:23
Show Gist options
  • Save chrishulbert/3d720a0c09b02d8a958e to your computer and use it in GitHub Desktop.
Save chrishulbert/3d720a0c09b02d8a958e to your computer and use it in GitHub Desktop.
//
// Keychain.swift
// SwiftKeychain
//
// Created by Chris Hulbert on 14/06/2015.
// Copyright (c) 2015 Chris Hulbert. All rights reserved.
//
import Foundation
import Security
struct Keychain {
static func deleteItemForKey(key: String) {
let query = [
kSecClass as NSString: kSecClassGenericPassword,
kSecAttrLabel: key,
]
SecItemDelete(query)
}
static func itemForKey(key: String) -> NSData? {
let query = [
kSecClass as NSString: kSecClassGenericPassword,
kSecAttrLabel: key,
kSecReturnData: kCFBooleanTrue as CFTypeRef,
]
var unmanagedResult: Unmanaged<AnyObject>?
// The '&' below converts it to UnsafeMutablePointer<Unmanaged<AnyObject>?>
let status = SecItemCopyMatching(query, &unmanagedResult)
// The 'create rule' means the returned result is +1 retained, so we need to balance that.
let result: AnyObject? = unmanagedResult?.takeRetainedValue()
return status == errSecSuccess ? result as? NSData : nil;
}
static func setItem(item: NSData, forKey key: String) {
self.deleteItemForKey(key) // Remove the item if it exists.
let query = [
kSecClass as NSString: kSecClassGenericPassword,
kSecAttrLabel: key,
kSecValueData: item,
]
SecItemAdd(query, nil);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment