0

I am going to build a powerful contact app. I have successfully fetched all contacts, but I am facing difficulties in fetching contact notes. When I add the 'notes' key, some contacts are missing from the table view. Here is the fetch keys code:

private func fetchContacts() {
DispatchQueue.global().async {
    let store = CNContactStore()
    let keysToFetch = [
        // add keys here
        CNContactNoteKey
    ] as [CNKeyDescriptor]
    let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)

    do {
        var contactsArray: [CNContact] = []
        var existingSectionTitles: [String] = []

        try store.enumerateContacts(with: fetchRequest) { contact, _ in
            contactsArray.append(contact)
            let title = String(contact.givenName.prefix(1).uppercased())
            if !existingSectionTitles.contains(title) {
                existingSectionTitles.append(title)
            }
        }

        let sortedTitles = existingSectionTitles.sorted()

        DispatchQueue.main.async {
            contacts = contactsArray
            sectionIndexTitles = sortedTitles
        }
    } catch {
        print("Failed to fetch contacts: \(error)")
    }
  }
}

Create the first table view to display a list of contacts. Implement the functionality for selecting a contact from the first table view. Create the second table view specifically for displaying contact details and notes. Retrieve the contact notes for the selected contact. Provide the ability to add notes for the selected contact in the second table view:

import Contacts

struct ContactInfoTableView: View { let contact: CNContact

var notes: String? {
    contact.note
}

// ... your existing fetch contacts code ...

var body: some View {
    List {
        // ... your existing fetch contacts code ...
        
        if let notes = notes, !notes.isEmpty {
            Section(header: Text("Notes").font(.system(size: 15, weight: .bold))) {
                Text(notes)
                    .font(.subheadline)
                    .foregroundColor(.gray)
            }
        }
    }
    .listStyle(InsetGroupedListStyle())
  }
}

I am fully aware that adding the 'com.apple.developer.contacts.notes' entitlement allows me to fetch contact notes. However, when I add the 'notes' key, the first table view stops displaying some contacts. Do you have any ideas on how to prevent this issue and ensure that all contacts are still displayed in the first table view?

Antonio Adrian Chavez
  • 1,016
  • 1
  • 7
  • 12

0 Answers0