PluginBench
Skill
Pass
Audit score 90

contacts-framework

dpearson2699/swift-ios-skills

Read, create, update, and pick contacts using Contacts and ContactsUI frameworks.

What is contacts-framework?

Provides access to the user's Contacts database via CNContactStore, CNSaveRequest, and CNContactPickerViewController. Use this skill when you need to fetch contact data, create or modify contacts, handle contact permissions, or present a contact picker UI in SwiftUI.

  • Fetch contacts by name, identifier, or enumerate all contacts with configurable key descriptors
  • Create new contacts and update existing contacts using CNMutableContact and CNSaveRequest
  • Delete contacts from the Contacts database
  • Present CNContactPickerViewController in SwiftUI without requiring full Contacts access
  • Handle contact authorization states including limited access (iOS 18+)
  • Access contact properties like phone numbers, emails, addresses, photos, and birthdays

How to install contacts-framework

npx skills add https://github.com/dpearson2699/swift-ios-skills --skill contacts-framework
Prerequisites
  • Add NSContactsUsageDescription to Info.plist explaining contact access
  • Add com.apple.developer.contacts.notes entitlement only if reading/writing contact notes (requires Apple approval)
  • Target Swift 6.3 / iOS 26+
Claude Code
Cursor
Windsurf
Cline

How to use contacts-framework

  1. 1.Request contact access using CNContactStore.requestAccess(for:) and check authorization status
  2. 2.Define the contact properties you need using key descriptors (CNContactGivenNameKey, CNContactPhoneNumbersKey, etc.)
  3. 3.Fetch contacts using unifiedContacts(matching:keysToFetch:) for predicate queries or enumerateContacts(with:usingBlock:) for batch enumeration
  4. 4.To create a contact, instantiate CNMutableContact, set properties, wrap in CNSaveRequest, and execute via store.execute()
  5. 5.To update a contact, fetch it with required keys, create a mutable copy, modify properties, and save via CNSaveRequest
  6. 6.To present a contact picker in SwiftUI, wrap CNContactPickerViewController using UIViewControllerRepresentable

Use cases

Good for
  • Building a messaging or calling app that needs to look up user phone numbers or emails
  • Creating a contact management interface that allows users to add, edit, or remove contacts
  • Implementing a contact picker to let users select a contact without granting full Contacts access
  • Syncing app-created contacts with the system Contacts database
  • Displaying contact photos and formatted names in a contacts list view
Who it's for
  • iOS app developers building contact-related features
  • SwiftUI developers wrapping UIKit contact components
  • Apps requiring contact read/write access with proper permission handling

contacts-framework FAQ

Do I need special permissions to use CNContactPickerViewController?

No. The contact picker does not require authorization—the system grants access only to the contacts the user selects from the picker.

What happens if I access a contact property that wasn't fetched?

It throws CNContactPropertyNotFetchedException. Always include the properties you need in the keysToFetch array.

How do I handle limited contact access on iOS 18+?

Treat .limited authorization status as usable. Fetch, edit, and delete operations apply only to contacts the user granted or the app created. Use ContactAccessButton or contactAccessPicker to let users add contacts to the app's limited-access set.

Can I update a contact without fetching all its properties first?

No. You must fetch the contact with the properties you intend to modify, create a mutable copy, change those properties, then save.

What's the difference between unifiedContacts and enumerateContacts?

unifiedContacts(matching:keysToFetch:) is for predicate-based queries returning a single array. enumerateContacts(with:usingBlock:) is for batch enumeration of all contacts and is better for large address books; perform it off the main thread.

Full instructions (SKILL.md)

Source of truth, from dpearson2699/swift-ios-skills.


name: contacts-framework description: "Read, create, update, and pick contacts using the Contacts and ContactsUI frameworks. Use when fetching contact data, saving new contacts, wrapping CNContactPickerViewController in SwiftUI, handling contact permissions, or working with CNContactStore fetch and save requests."

Contacts Framework

Fetch, create, update, and pick contacts from the user's Contacts database using CNContactStore, CNSaveRequest, and CNContactPickerViewController. Targets Swift 6.3 / iOS 26+.

Contents

Setup

Project Configuration

  1. Add NSContactsUsageDescription to Info.plist explaining why the app accesses contacts. The app crashes if it uses contact data APIs without this key.
  2. No additional capability or entitlement is required for ordinary Contacts access.
  3. Add com.apple.developer.contacts.notes only when reading or writing CNContactNoteKey / CNContact.note; this entitlement requires Apple approval before public distribution.

Imports

@preconcurrency import Contacts  // CNContactStore, CNSaveRequest, CNContact
import ContactsUI                // CNContactPickerViewController

Authorization

Request access before fetching or saving contacts. The picker (CNContactPickerViewController) does not require authorization -- the system grants access only to the contacts the user selects.

let store = CNContactStore()

func requestAccess() async throws -> Bool {
    return try await store.requestAccess(for: .contacts)
}

// Check current status without prompting
func checkStatus() -> CNAuthorizationStatus {
    CNContactStore.authorizationStatus(for: .contacts)
}

Authorization States

StatusMeaning
.notDeterminedUser has not been prompted yet
.authorizedFull read/write access granted
.deniedUser denied access; direct to Settings
.restrictedParental controls or MDM restrict access
.limitediOS 18+: user granted access to selected contacts only

Treat both .authorized and .limited as usable Contacts API states. With .limited, fetch, edit, and delete operations only apply to contacts the user granted or the app created. Use ContactAccessButton or contactAccessPicker(isPresented:completionHandler:) to let users add contacts to the app's limited-access set.

Fetching Contacts

Use unifiedContacts(matching:keysToFetch:) for predicate-based queries. Use enumerateContacts(with:usingBlock:) for batch enumeration of all contacts. For large cached address books, first fetch identifiers, then fetch detailed contacts in batches by identifier.

Fetch by Name

func fetchContacts(named name: String) throws -> [CNContact] {
    let predicate = CNContact.predicateForContacts(matchingName: name)
    let keys: [CNKeyDescriptor] = [
        CNContactGivenNameKey as CNKeyDescriptor,
        CNContactFamilyNameKey as CNKeyDescriptor,
        CNContactPhoneNumbersKey as CNKeyDescriptor
    ]
    return try store.unifiedContacts(matching: predicate, keysToFetch: keys)
}

Fetch by Identifier

func fetchContact(identifier: String) throws -> CNContact {
    let keys: [CNKeyDescriptor] = [
        CNContactGivenNameKey as CNKeyDescriptor,
        CNContactFamilyNameKey as CNKeyDescriptor,
        CNContactEmailAddressesKey as CNKeyDescriptor
    ]
    return try store.unifiedContact(withIdentifier: identifier, keysToFetch: keys)
}

Enumerate All Contacts

Perform I/O-heavy enumeration off the main thread.

func fetchAllContacts() throws -> [CNContact] {
    let keys: [CNKeyDescriptor] = [
        CNContactGivenNameKey as CNKeyDescriptor,
        CNContactFamilyNameKey as CNKeyDescriptor
    ]
    let request = CNContactFetchRequest(keysToFetch: keys)
    request.sortOrder = .givenName

    var contacts: [CNContact] = []
    try store.enumerateContacts(with: request) { contact, _ in
        contacts.append(contact)
    }
    return contacts
}

Key Descriptors

Only fetch the properties you need. Accessing an unfetched property throws CNContactPropertyNotFetchedException.

Common Keys

KeyProperty
CNContactGivenNameKeyFirst name
CNContactFamilyNameKeyLast name
CNContactPhoneNumbersKeyPhone numbers array
CNContactEmailAddressesKeyEmail addresses array
CNContactPostalAddressesKeyMailing addresses array
CNContactImageDataKeyFull-resolution contact photo
CNContactThumbnailImageDataKeyThumbnail contact photo
CNContactBirthdayKeyBirthday date components
CNContactOrganizationNameKeyCompany name

Composite Key Descriptors

Use CNContactFormatter.descriptorForRequiredKeys(for:) to fetch all keys needed for formatting a contact's name.

let nameKeys = CNContactFormatter.descriptorForRequiredKeys(for: .fullName)
let keys: [CNKeyDescriptor] = [nameKeys, CNContactPhoneNumbersKey as CNKeyDescriptor]

Creating and Updating Contacts

Use CNMutableContact to build new contacts and CNSaveRequest to persist changes.

Creating a New Contact

func createContact(givenName: String, familyName: String, phone: String) throws {
    let contact = CNMutableContact()
    contact.givenName = givenName
    contact.familyName = familyName
    contact.phoneNumbers = [
        CNLabeledValue(
            label: CNLabelPhoneNumberMobile,
            value: CNPhoneNumber(stringValue: phone)
        )
    ]

    let saveRequest = CNSaveRequest()
    saveRequest.add(contact, toContainerWithIdentifier: nil) // nil = default container
    try store.execute(saveRequest)
}

Updating an Existing Contact

You must fetch the contact with the properties you intend to modify, create a mutable copy, change the properties, then save.

func updateContactEmail(identifier: String, email: String) throws {
    let keys: [CNKeyDescriptor] = [
        CNContactEmailAddressesKey as CNKeyDescriptor
    ]
    let contact = try store.unifiedContact(withIdentifier: identifier, keysToFetch: keys)
    guard let mutable = contact.mutableCopy() as? CNMutableContact else { return }

    mutable.emailAddresses.append(
        CNLabeledValue(label: CNLabelWork, value: email as NSString)
    )

    let saveRequest = CNSaveRequest()
    saveRequest.update(mutable)
    try store.execute(saveRequest)
}

Deleting a Contact

func deleteContact(identifier: String) throws {
    let keys: [CNKeyDescriptor] = [CNContactIdentifierKey as CNKeyDescriptor]
    let contact = try store.unifiedContact(withIdentifier: identifier, keysToFetch: keys)
    guard let mutable = contact.mutableCopy() as? CNMutableContact else { return }

    let saveRequest = CNSaveRequest()
    saveRequest.delete(mutable)
    try store.execute(saveRequest)
}

Contact Picker

CNContactPickerViewController lets users pick contacts without granting full Contacts access. The app receives only the selected contact data.

SwiftUI Wrapper

import SwiftUI
import ContactsUI

struct ContactPicker: UIViewControllerRepresentable {
    @Binding var selectedContact: CNContact?

    func makeUIViewController(context: Context) -> CNContactPickerViewController {
        let picker = CNContactPickerViewController()
        picker.delegate = context.coordinator
        return picker
    }

    func updateUIViewController(_ uiViewController: CNContactPickerViewController, context: Context) {}

    func makeCoordinator() -> Coordinator {
        Coordinator(self)
    }

    final class Coordinator: NSObject, CNContactPickerDelegate {
        let parent: ContactPicker

        init(_ parent: ContactPicker) {
            self.parent = parent
        }

        func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {
            parent.selectedContact = contact
        }

        func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
            parent.selectedContact = nil
        }
    }
}

Using the Picker

struct ContactSelectionView: View {
    @State private var selectedContact: CNContact?
    @State private var showPicker = false

    var body: some View {
        VStack {
            if let contact = selectedContact {
                Text("\(contact.givenName) \(contact.familyName)")
            }
            Button("Select Contact") {
                showPicker = true
            }
        }
        .sheet(isPresented: $showPicker) {
            ContactPicker(selectedContact: $selectedContact)
        }
    }
}

Filtering the Picker

Use predicates to control which contacts appear and what the user can select.

let picker = CNContactPickerViewController()
// Only show contacts that have an email address
picker.predicateForEnablingContact = NSPredicate(format: "emailAddresses.@count > 0")
// Selecting a contact returns it directly (no detail card)
picker.predicateForSelectionOfContact = NSPredicate(value: true)

Observing Changes

Listen for external contact database changes to refresh cached data.

func observeContactChanges() {
    NotificationCenter.default.addObserver(
        forName: .CNContactStoreDidChange,
        object: nil,
        queue: .main
    ) { _ in
        // Refetch contacts -- cached CNContact objects are stale
        refreshContacts()
    }
}

Common Mistakes

DON'T: Fetch all keys when you only need a name

Over-fetching wastes memory and slows queries, especially for contacts with large photos.

// WRONG: Fetches far more than the UI displays, including full-resolution photos
let keys: [CNKeyDescriptor] = [
    CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
    CNContactImageDataKey as CNKeyDescriptor,
    CNContactPhoneNumbersKey as CNKeyDescriptor,
    CNContactEmailAddressesKey as CNKeyDescriptor,
    CNContactPostalAddressesKey as CNKeyDescriptor,
    CNContactBirthdayKey as CNKeyDescriptor
]

// CORRECT: Fetch only what you display
let keys: [CNKeyDescriptor] = [
    CNContactGivenNameKey as CNKeyDescriptor,
    CNContactFamilyNameKey as CNKeyDescriptor
]

DON'T: Access unfetched properties

Accessing a property that was not in keysToFetch throws CNContactPropertyNotFetchedException at runtime.

// WRONG: Only fetched name keys, now accessing phone
let keys: [CNKeyDescriptor] = [CNContactGivenNameKey as CNKeyDescriptor]
let contact = try store.unifiedContact(withIdentifier: id, keysToFetch: keys)
let phone = contact.phoneNumbers.first // CRASH

// CORRECT: Include the key you need
let keys: [CNKeyDescriptor] = [
    CNContactGivenNameKey as CNKeyDescriptor,
    CNContactPhoneNumbersKey as CNKeyDescriptor
]

DON'T: Mutate a CNContact directly

CNContact is immutable. You must call mutableCopy() to get a CNMutableContact.

// WRONG: CNContact has no setter
let contact = try store.unifiedContact(withIdentifier: id, keysToFetch: keys)
contact.givenName = "New Name" // Compile error

// CORRECT: Create mutable copy
guard let mutable = contact.mutableCopy() as? CNMutableContact else { return }
mutable.givenName = "New Name"

DON'T: Skip authorization and assume access

Do not let fetch or save calls be the first place the user sees authorization. If status is .notDetermined, request access; if access was denied, contact operations fail with an authorization error.

// WRONG: Jump straight to fetch
let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keys)

// CORRECT: Check or request access first
let granted = try await store.requestAccess(for: .contacts)
guard granted else { return }
let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keys)

DON'T: Run heavy fetches on the main thread

enumerateContacts performs I/O. Running it on the main thread blocks the UI. When strict concurrency checks complain about CNContact crossing task or actor boundaries, use @preconcurrency import Contacts in that file or map contacts into Sendable view models before returning them.

// WRONG: Main thread enumeration
func loadContacts() {
    try store.enumerateContacts(with: request) { contact, _ in ... }
}

// CORRECT: Run on a background thread
func loadContacts() async throws -> [CNContact] {
    try await Task.detached {
        var results: [CNContact] = []
        try store.enumerateContacts(with: request) { contact, _ in
            results.append(contact)
        }
        return results
    }.value
}

Review Checklist

  • NSContactsUsageDescription added to Info.plist
  • requestAccess(for: .contacts) called before fetch or save operations
  • .limited treated as usable access with selected-contact caveats
  • ContactAccessButton or contactAccessPicker offered when users need to expand limited access
  • Authorization denial handled gracefully (guide user to Settings)
  • Only needed CNKeyDescriptor keys included in fetch requests
  • CNContactFormatter.descriptorForRequiredKeys(for:) used when formatting names
  • Mutable copy created via mutableCopy() before modifying contacts
  • CNSaveRequest used for all create/update/delete operations
  • Heavy fetches (enumerateContacts) run off the main thread
  • CNContactStoreDidChange observed to refresh cached contacts
  • CNContactPickerViewController used when full Contacts access is unnecessary
  • Picker predicates set before presenting the picker view controller
  • Single CNContactStore instance reused across the app

References

Related skills

More from dpearson2699/swift-ios-skills and the wider catalog.

COcore-bluetooth logo

core-bluetooth

dpearson2699/swift-ios-skills

Build Bluetooth Low Energy central and peripheral workflows with Core Bluetooth scanning, connecting, GATT communication, and background modes.

2.2k installsAudited
COcore-data logo

core-data

dpearson2699/swift-ios-skills

Build, review, or improve Core Data persistence in apps that have not adopted SwiftData. Use when working with NSManagedObject subclasses, NSFetchedResultsController for list-driven UI, NSBatchInsertRequest / NSBatchDeleteRequest / NSBatchUpdateRequest for bulk operations, NSPersistentHistoryChangeRequest for persistent history tracking and multi-target sync, NSStagedMigrationManager for staged schema migrations (iOS 17+), NSCompositeAttributeDescription for composite attributes (iOS 17+), or when integrating Core Data threading with Swift Concurrency. For Core Data + SwiftData coexistence or migration, see the swiftdata skill instead.

1.1k installsAudited
COcore-motion logo

core-motion

dpearson2699/swift-ios-skills

Access iOS/watchOS device sensors: accelerometer, gyroscope, magnetometer, pedometer, activity recognition, altitude, and motion data.

2.1k installsAudited
COcore-nfc logo

core-nfc

dpearson2699/swift-ios-skills

Read and write NFC tags on iPhone using CoreNFC framework.

2.1k installs
COcoreml logo

coreml

dpearson2699/swift-ios-skills

Load, configure, and run Core ML models in iOS apps with on-device inference.

2.2k installsAudited
CRcryptokit logo

cryptokit

dpearson2699/swift-ios-skills

Apple CryptoKit for Swift cryptographic primitives: hashing, encryption, signing, and key exchange.

1.6k installsAudited