0

I am using UserDefaults to store and retrieve name and password details but now i want to store name and password details in keychain for security purpose. I have gone through so many tutorials but i do not understand. is it necessary to add any git framework or we can save and retrieve name and password details manually. if it necessary to add git framework then please suggest me the best keychain framework in swift to store name and password.

below is my code in UserDefaults:

in registration viewcontroller

UserDefaults.standard.set(regNameTextField.text, forKey: "name")
UserDefaults.standard.set(regPasswordTextField.text, forKey: "password")

in login viewcontroller

let storedregName = UserDefaults.standard.value(forKey: "name") as! String
let storedregPassword = UserDefaults.standard.value(forKey: "password") as! String

anyone can guide me here.

Swift
  • 1,074
  • 12
  • 46
  • you will find Possible best solution answer here [enter link description here](https://stackoverflow.com/questions/37539997/save-and-load-from-keychain-swift) – Vishal Davara May 16 '19 at 12:04

1 Answers1

1

Take a look to this example:

Define a structure to hold the credentials as they move around your app in memory:

struct Credentials {
    var username: String
    var password: String
}

Next, define an error enumeration that you can use to communicate keychain access outcomes:

enum KeychainError: Error {
    case noPassword
    case unexpectedPasswordData
    case unhandledError(status: OSStatus)
}

Then, identify the server that your app is working with:

static let server = "www.example.com"

Create an Add Query Using an instance of the credentials structure and the server constant, you can create an add query:

let account = credentials.username
let password = credentials.password.data(using: String.Encoding.utf8)!
var query: [String: Any] = [kSecClass as String: kSecClassInternetPassword,
                            kSecAttrAccount as String: account,
                            kSecAttrServer as String: server,
                            kSecValueData as String: password]

Add the Item With the query complete, you simply feed it to the SecItemAdd(_:_:) function:

let status = SecItemAdd(query as CFDictionary, nil)
guard status == errSecSuccess else { throw KeychainError.unhandledError(status: status) }

Source

Pedro Trujillo
  • 1,559
  • 18
  • 19