Menggunakan Keychain dgn Swift

Username dan Password, kalau memang harus disimpan di device disarankan menggunakan Keychain. JANGAN disimpan menggunakan NSUserDefault maupun CoreData. Dengan sedikit googling ketemu ada yang sudah membuat wrappernya dalam bahasa Swift, di sini. Langsung saja saya tuliskan code untuk menggunakannya di bawah ini:

 



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!)")
        
    }
}