Last active
August 29, 2015 14:23
-
-
Save chrishulbert/3d720a0c09b02d8a958e to your computer and use it in GitHub Desktop.
Revisions
-
chrishulbert revised this gist
Jun 14, 2015 . 1 changed file with 5 additions and 7 deletions.There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -28,16 +28,14 @@ struct Keychain { 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, -
chrishulbert created this gist
Jun 14, 2015 .There are no files selected for viewing
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 charactersOriginal file line number Diff line number Diff line change @@ -0,0 +1,49 @@ // // 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); } }