Advertisement
Guest User

Untitled

a guest
Apr 6th, 2019
109
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.43 KB | None | 0 0
  1. class KeyChainManager {
  2.  
  3. static func saveGenericPassword(service:String, account:String, password:String) -> Void {
  4. let account = userNameTextField.text
  5. let passwordUtf8 = password.data(using: String.Encoding.utf8)!
  6. let addquery: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
  7. kSecAttrAccount as String: account!,
  8. kSecAttrService as String: service ,
  9. kSecValueData as String: passwordUtf8!]
  10.  
  11. let status = SecItemAdd(addquery as CFDictionary, nil)
  12. guard status == errSecSuccess else {
  13. os_log("%{public}@", type: .debug, "Error saving to keychain \(status)")
  14. return
  15. }
  16. os_log("%{public}@", type: .debug, "success saving to keychain \(status)")
  17. }
  18.  
  19. static func retrieveGenericPassword(service:String, account:String, password:String) -> String {
  20. let user = account
  21. let getquery: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
  22. kSecAttrAccount as String: user!,
  23. kSecAttrService as String: service,
  24. kSecMatchLimit as String: kSecMatchLimitOne,
  25. kSecReturnAttributes as String: true,
  26. kSecReturnData as String: true]
  27.  
  28. var item: CFTypeRef?
  29. let status = SecItemCopyMatching(getquery as CFDictionary, &item)
  30.  
  31.  
  32. guard status != errSecItemNotFound else {
  33. os_log("%{public}@", type: .debug, "Error: \(KeychainError.noPassword)")
  34. return
  35. }
  36. guard status == errSecSuccess else {
  37. os_log("%{public}@", type: .debug, "unhandledError: \(KeychainError.unhandledError(status: status))")
  38. return
  39. }
  40.  
  41.  
  42. guard let existingItem = item as? [String : Any],
  43. let passwordData = existingItem[kSecValueData as String] as? Data,
  44. let password = String(data: passwordData, encoding: String.Encoding.utf8),
  45. let accountRetrieved = existingItem[kSecAttrAccount as String] as? String
  46. else {
  47. os_log("%{public}@", type: .debug, "unexpectedPasswordData: \(KeychainError.unexpectedPasswordData)")
  48. return
  49. }
  50. return password
  51. }
  52.  
  53. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement