Last active
August 29, 2015 14:23
-
-
Save chrishulbert/3d720a0c09b02d8a958e to your computer and use it in GitHub Desktop.
This file contains hidden or 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) | |
| if status == errSecSuccess { // Successful? | |
| if let unmanagedResult = unmanagedResult { // Returned anything? | |
| let result: AnyObject = unmanagedResult.takeRetainedValue() // Manage its memory. | |
| return result as? NSData // Auto-nil if it's not an NSData. | |
| } | |
| } | |
| return nil | |
| } | |
| static func setItem(item: NSData, forKey key: String) { | |
| 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