[swift] 연락처(Contacts) 정보에 대한 사용자 정의 필드 추가하는 방법

여기에는 몇 단계가 필요합니다. 먼저, Contacts 프레임워크를 사용할 수 있도록 프로젝트에 추가해야 합니다. 그런 다음, 사용자 정의 연락처 필드를 생성하고, 해당 필드를 사용하여 연락처 정보를 읽거나 쓸 수 있습니다.

다음은 간단한 예제 코드입니다.

import Contacts
import ContactsUI

let store = CNContactStore()

// 1. 권한 요청
store.requestAccess(for: .contacts) { granted, error in
    guard granted else {
        // 사용자가 액세스 권한을 부여하지 않은 경우
        return
    }

    // 2. 사용자 정의 연락처 필드 생성
    let customLabel = CNLabeledValue(label: "Custom Label", value: "Custom Value")

    // 3. 새로운 연락처 생성
    let newContact = CNMutableContact()
    newContact.givenName = "John"
    newContact.familyName = "Doe"
    newContact.phoneNumbers = [CNLabeledValue(label: CNLabelPhoneNumberMain, value: CNPhoneNumber(stringValue: "1234567890")),
                                customLabel]

    // 4. 연락처 저장
    let saveRequest = CNSaveRequest()
    saveRequest.add(newContact, toContainerWithIdentifier: store.defaultContainerIdentifier())

    do {
        try store.execute(saveRequest)
    } catch {
        // 오류 처리
    }
}

이 코드는 사용자에게 연락처 액세스 권한을 요청한 후, “Custom Label”이라는 사용자 정의 필드를 추가하여 “John Doe”라는 새로운 연락처를 생성하고 저장합니다.

이 코드를 실행하면 연락처 앱에 “John Doe”의 연락처가 추가되고, 추가한 사용자 정의 필드가 함께 표시됩니다.

더 자세한 정보는 Apple 공식 문서를 참조하세요.