Skip to content

Instantly share code, notes, and snippets.

@mhomol
Created September 17, 2015 13:20
Show Gist options
  • Select an option

  • Save mhomol/a7be3e88f142d96e0ea5 to your computer and use it in GitHub Desktop.

Select an option

Save mhomol/a7be3e88f142d96e0ea5 to your computer and use it in GitHub Desktop.

Revisions

  1. mhomol created this gist Sep 17, 2015.
    25 changes: 25 additions & 0 deletions saveLogin.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,25 @@
    //Don't forget to add the Security.framework to your project.
    import Security
    private let kSecClassValue = NSString(format: kSecClass)
    private let kSecAttrAccountValue = NSString(format: kSecAttrAccount)
    private let kSecValueDataValue = NSString(format: kSecValueData)
    private let kSecClassGenericPasswordValue = NSString(format: kSecClassGenericPassword)
    private let kSecAttrServiceValue = NSString(format: kSecAttrService)
    private let kSecMatchLimitValue = NSString(format: kSecMatchLimit)
    private let kSecReturnDataValue = NSString(format: kSecReturnData)
    private let kSecMatchLimitOneValue = NSString(format: kSecMatchLimitOne)

    func saveLogin(password: NSData, userName:String, service:String)
    {
    //Create the query
    var keychainQuery: NSMutableDictionary = NSMutableDictionary(objects: [kSecClassGenericPasswordValue, service, userName, password], forKeys: [kSecClassValue, kSecAttrServiceValue, kSecAttrAccountValue, kSecValueDataValue])

    // Delete any existing items
    SecItemDelete(keychainQuery as CFDictionaryRef)

    //Add the query to the keychain
    var status: OSStatus = SecItemAdd(keychainQuery as CFDictionaryRef, nil)

    //Verify the status and handle your error, status of 0 means everything worked
    println(status)
    }