[swift] Swift에서 키체인을 사용하여 고객 정보 관리하기

앱 개발 시에는 사용자의 개인 정보를 안전하게 저장하기 위해 키체인(Keychain)을 사용하는 것이 일반적입니다. 키체인은 iOS 및 macOS에서 제공하는 운영 체제 수준의 안전한 저장소입니다.

이번 튜토리얼에서는 Swift에서 키체인을 사용하여 고객 정보를 관리하는 방법에 대해 알아보겠습니다.

1. 키체인 라이브러리 가져오기

Swift에서 키체인을 사용하기 위해서는 Security.framework를 프로젝트에 추가해야 합니다. 이를 위해 다음 단계를 따릅니다:

  1. 프로젝트를 선택하고 타겟을 선택합니다.
  2. Build Phases 탭으로 이동합니다.
  3. Link Binary With Libraries 섹션에서 “+” 버튼을 클릭합니다.
  4. Security.framework을 선택하고 Add 버튼을 클릭합니다.

2. 키체인에 데이터 저장하기

키체인을 사용하여 고객 정보를 저장하기 위해서는 다음과 같은 단계를 따릅니다:

import Security

// 키의 이름과 값 설정
let service = "com.example.app"
let account = "customer"
let value = "John Doe"

// 키체인에 값 저장
if let valueData = value.data(using: .utf8) {
    let query: [String: Any] = [
        kSecClass as String: kSecClassGenericPassword,
        kSecAttrService as String: service,
        kSecAttrAccount as String: account,
        kSecValueData as String: valueData
    ]
    
    let status = SecItemAdd(query as CFDictionary, nil)
    
    if status == errSecSuccess {
        print("Data saved to Keychain")
    } else {
        print("Failed to save data to Keychain")
    }
}

3. 키체인에서 데이터 가져오기

키체인에서 저장된 데이터를 가져오기 위해서는 다음과 같은 단계를 따릅니다:

import Security

// 가져올 키의 이름과 값 설정
let service = "com.example.app"
let account = "customer"

// 키체인에서 값 가져오기
let query: [String: Any] = [
    kSecClass as String: kSecClassGenericPassword,
    kSecAttrService as String: service,
    kSecAttrAccount as String: account,
    kSecMatchLimit as String: kSecMatchLimitOne,
    kSecReturnData as String: true
]

var item: CFTypeRef?
let status = SecItemCopyMatching(query as CFDictionary, &item)

if status == errSecSuccess, let data = item as? Data, let value = String(data: data, encoding: .utf8) {
    print("Value retrieved from Keychain: \(value)")
} else {
    print("Failed to retrieve value from Keychain")
}

요약

이번 튜토리얼에서는 Swift에서 키체인을 사용하여 고객 정보를 관리하는 방법에 대해 알아보았습니다. 키체인은 개인 정보를 안전하게 저장하기 위한 운영 체제 수준의 저장소이며, Security.framework를 사용하여 Swift에서 키체인을 사용할 수 있습니다. 키체인에 데이터를 저장하고 가져오는 방법을 순서대로 설명했으니, 앱 개발 시에 개인 정보를 안전하게 관리하기 위해 키체인을 활용해 보시기 바랍니다.

참고 문서