0
0
iOS Swiftmobile~5 mins

Keychain for secure storage in iOS Swift

Choose your learning style9 modes available
Introduction

Keychain helps you keep sensitive data safe on your iPhone. It stores passwords and keys securely so only your app can access them.

Saving a user password after login to avoid asking every time.
Storing an authentication token securely for API calls.
Keeping a secret key for encrypting user data.
Saving sensitive user preferences that should not be visible.
Remembering login credentials safely between app launches.
Syntax
iOS Swift
import Security

// To save data
let query: [String: Any] = [
  kSecClass as String: kSecClassGenericPassword,
  kSecAttrAccount as String: "userEmail",
  kSecValueData as String: "user@example.com".data(using: .utf8)!
]
SecItemAdd(query as CFDictionary, nil)

// To read data
let query: [String: Any] = [
  kSecClass as String: kSecClassGenericPassword,
  kSecAttrAccount as String: "userEmail",
  kSecReturnData as String: kCFBooleanTrue!
]
var item: CFTypeRef?
SecItemCopyMatching(query as CFDictionary, &item)

Use kSecClassGenericPassword for most secure storage needs.

Always convert strings to Data before saving.

Examples
This saves an API token securely in the keychain.
iOS Swift
let addQuery: [String: Any] = [
  kSecClass as String: kSecClassGenericPassword,
  kSecAttrAccount as String: "apiToken",
  kSecValueData as String: "12345abcde".data(using: .utf8)!
]
SecItemAdd(addQuery as CFDictionary, nil)
This reads the saved API token from the keychain and prints it.
iOS Swift
let getQuery: [String: Any] = [
  kSecClass as String: kSecClassGenericPassword,
  kSecAttrAccount as String: "apiToken",
  kSecReturnData as String: kCFBooleanTrue!
]
var result: CFTypeRef?
let status = SecItemCopyMatching(getQuery as CFDictionary, &result)
if status == errSecSuccess, let data = result as? Data, let token = String(data: data, encoding: .utf8) {
  print("Token: \(token)")
}
Sample App

This app saves a password securely in the keychain and then reads it back. It prints messages to the console to show success or failure.

iOS Swift
import UIKit
import Security

class ViewController: UIViewController {
  override func viewDidLoad() {
    super.viewDidLoad()

    let account = "userEmail"
    let password = "secret123"

    // Save password
    let addQuery: [String: Any] = [
      kSecClass as String: kSecClassGenericPassword,
      kSecAttrAccount as String: account,
      kSecValueData as String: password.data(using: .utf8)!
    ]
    SecItemDelete(addQuery as CFDictionary) // Remove old item if exists
    let status = SecItemAdd(addQuery as CFDictionary, nil)

    if status == errSecSuccess {
      print("Password saved successfully.")
    } else {
      print("Failed to save password.")
    }

    // Retrieve password
    let getQuery: [String: Any] = [
      kSecClass as String: kSecClassGenericPassword,
      kSecAttrAccount as String: account,
      kSecReturnData as String: kCFBooleanTrue!
    ]
    var result: CFTypeRef?
    let copyStatus = SecItemCopyMatching(getQuery as CFDictionary, &result)

    if copyStatus == errSecSuccess, let data = result as? Data, let savedPassword = String(data: data, encoding: .utf8) {
      print("Retrieved password: \(savedPassword)")
    } else {
      print("Failed to retrieve password.")
    }
  }
}
OutputSuccess
Important Notes

Always delete old keychain items before adding new ones with the same key to avoid duplicates.

Keychain data persists even if the app is deleted and reinstalled unless you change the keychain access group.

Test keychain code on a real device because the simulator may behave differently.

Summary

Keychain stores sensitive data securely on iOS devices.

Use SecItemAdd to save and SecItemCopyMatching to read data.

Always convert strings to Data before saving and back to strings after reading.