How to Use Keychain In Swift

Username and Password, if need to be save, don't store it using NSUserDefault or in CoreData! Use Keychain instead, it is safer.

With a litle bit of googling, we can find somebody has already written a wrapper for this work here. Below I show you how to use that wrapper



import UIKit
import Security

class Keychain {
    
    class func save(key: String, data: NSData) -> Bool {
        let query = [
            kSecClass as String       : kSecClassGenericPassword as String,
            kSecAttrAccount as String : key,
            kSecValueData as String   : data ]
        
        SecItemDelete(query as CFDictionaryRef)
        
        let status: OSStatus = SecItemAdd(query as CFDictionaryRef, nil)
        
        return status == noErr
    }
    
    class func load(key: String) -> NSData? {
        let query = [
            kSecClass as String       : kSecClassGenericPassword,
            kSecAttrAccount as String : key,
            kSecReturnData as String  : kCFBooleanTrue,
            kSecMatchLimit as String  : kSecMatchLimitOne ]
        
        var dataTypeRef :Unmanaged?
        
        let status: OSStatus = SecItemCopyMatching(query, &dataTypeRef)
        
        if status == noErr {
            return (dataTypeRef!.takeRetainedValue() as NSData)
        } else {
            return nil
        }
    }
    
    class func delete(key: String) -> Bool {
        let query = [
            kSecClass as String       : kSecClassGenericPassword,
            kSecAttrAccount as String : key ]
        
        let status: OSStatus = SecItemDelete(query as CFDictionaryRef)
        
        return status == noErr
    }
    
    
    class func clear() -> Bool {
        let query = [ kSecClass as String : kSecClassGenericPassword ]
        
        let status: OSStatus = SecItemDelete(query as CFDictionaryRef)
        
        return status == noErr
    }
    
}

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        //Oke kita coba simpan username dan password ke Keychain
        
        let username = ("tras" as NSString).dataUsingEncoding(NSASCIIStringEncoding)
        let password = ("rahasia" as NSString).dataUsingEncoding(NSASCIIStringEncoding)
        
        Keychain.save("username", data: username!)
        Keychain.save("password", data: password!)
    }
    
    override func viewDidAppear(animated: Bool) {
       //kemudian kita baca lagi 

        let username = NSString(data: Keychain.load("username")!, encoding: NSASCIIStringEncoding)
        let password = NSString(data: Keychain.load("password")!, encoding: NSASCIIStringEncoding)
        
        println("username : \(username!) & password : \(password!)")
        
    }
}