Last active
August 29, 2015 14:23
-
-
Save chrishulbert/3d720a0c09b02d8a958e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// | |
// 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