Skip to content

Instantly share code, notes, and snippets.

@seckincengiz
Forked from s-aska/Keychain.swift
Last active July 10, 2018 19:21
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seckincengiz/e4e2da2a712d30e39752e76afe300ca8 to your computer and use it in GitHub Desktop.
Save seckincengiz/e4e2da2a712d30e39752e76afe300ca8 to your computer and use it in GitHub Desktop.
Swift Keychain class ( supported Xcode 8.1 Beta and IOS 10.1 ) [swift3]
import UIKit
let scoresStringArray : [String] = ["Mike","Tom","Bily"]
let scoresDataArray = NSKeyedArchiver.archivedData(withRootObject: scoresStringArray)
//Save data
_ = Keychain.save(key: "scoresKey", data: scores)
//Load data
if Keychain.load(key: "scoresKey") != nil{
let scoresDataArray = Keychain.load(key: "scoresKey")!
let scoresStringArray = NSKeyedUnarchiver.unarchiveObject(with: scoresDataArray) as! [String]
print(scoresDataArray[1]) // Tom
}
import UIKit
import Security
class Keychain {
class func save(key: String, data: Data) -> Bool {
let query = [
kSecClass as String : kSecClassGenericPassword as String,
kSecAttrAccount as String : key,
kSecValueData as String : data ] as [String : Any]
SecItemDelete(query as CFDictionary)
let status: OSStatus = SecItemAdd(query as CFDictionary, nil)
return status == noErr
}
class func load(key: String) -> Data? {
let query = [
kSecClass as String : kSecClassGenericPassword,
kSecAttrAccount as String : key,
kSecReturnData as String : kCFBooleanTrue,
kSecMatchLimit as String : kSecMatchLimitOne ] as [String : Any]
var dataTypeRef: AnyObject?
let status = withUnsafeMutablePointer(to: &dataTypeRef) { SecItemCopyMatching(query as CFDictionary, UnsafeMutablePointer($0)) }
if status == errSecSuccess {
if let data = dataTypeRef as! Data? {
return data
}
}
return nil
}
class func delete(key: String) -> Bool {
let query = [
kSecClass as String : kSecClassGenericPassword,
kSecAttrAccount as String : key ] as [String : Any]
let status: OSStatus = SecItemDelete(query as CFDictionary)
return status == noErr
}
class func clear() -> Bool {
let query = [ kSecClass as String : kSecClassGenericPassword ]
let status: OSStatus = SecItemDelete(query as CFDictionary)
return status == noErr
}
}
@seckincengiz
Copy link
Author

For more info about apple keychain : https://www.apple.com/business/docs/iOS_Security_Guide.pdf

@eonist
Copy link

eonist commented Jun 14, 2017

@seckinburakcengiz Hey may I ask? What did you change? Love this lib.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment