Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- //
- // KeychainUtil.swift
- //
- // Created by Rodrigo Busata on 10/07/18.
- //
- import Foundation
- struct KeychainUtil {
- private static let server = Bundle.main.bundleIdentifier!
- static func saveCredentials(username: String, password: String) {
- let password = password.data(using: String.Encoding.utf8)!
- if self.getCredentials(byUsernamre: username) == nil {
- let query: [String: Any] = [kSecClass as String: kSecClassInternetPassword,
- kSecAttrServer as String: self.server,
- kSecAttrAccount as String: username,
- kSecValueData as String: password]
- let status = SecItemAdd(query as CFDictionary, nil)
- if status != errSecSuccess {
- print("Failed on saveCredentials() INSERT")
- }
- } else {
- let query: [String: Any] = [kSecClass as String: kSecClassInternetPassword,
- kSecAttrServer as String: self.server,
- kSecAttrAccount as String: username]
- let attributes: [String: Any] = [kSecValueData as String: password]
- let status = SecItemUpdate(query as CFDictionary, attributes as CFDictionary)
- if status != errSecSuccess {
- print("Failed on saveCredentials() UPDATE")
- }
- }
- }
- static func getCredentials(byUsernamre username: String) -> String? {
- let query: [String: Any] = [kSecClass as String: kSecClassInternetPassword,
- kSecAttrServer as String: self.server,
- kSecAttrAccount as String: username,
- kSecMatchLimit as String: kSecMatchLimitOne,
- kSecReturnAttributes as String: true,
- kSecReturnData as String: true]
- var item: CFTypeRef?
- let status = SecItemCopyMatching(query as CFDictionary, &item)
- if status == errSecItemNotFound {
- return nil
- }
- if status != errSecSuccess {
- print("Failed on getCredentials()")
- return nil
- }
- guard let existingItem = item as? [String : Any],
- let passwordData = existingItem[kSecValueData as String] as? Data,
- let password = String(data: passwordData, encoding: String.Encoding.utf8)
- else {
- return nil
- }
- return password
- }
- }
Add Comment
Please, Sign In to add comment