TEAM LICENSES: Save money and learn new skills through a Hacking with Swift+ team license >>

How do I create & update CNContacts on macOS?

Forums > macOS

@mtm  

I am struggling to understand managing Contacts via Swift on macOS. Any help with the two items below would be much appreciated.

  1. My attempts at creating a new CNContact fail with error message EXC_BAD_ACCESS (code=1, address=... at runtime. Code I have so far:
    var status: Bool = false

    store.requestAccess(for: CNEntityType.contacts) { hasPermission, error in
        if error != nil {
            print(error!)
        }
        status = hasPermission
    }

    let newContact = CNMutableContact()

    newContact.givenName = "NBED-given"
    newContact.familyName = "NBED-family"

    let saveRequest = CNSaveRequest()
    saveRequest.add(newContact, toContainerWithIdentifier: store.defaultContainerIdentifier())

    do {
        try store.execute(saveRequest)
    }
    catch {
        print("Error:\t\(error)")
    }
  1. Attempting to update an existing record appears to change the CNContact record, but the change is not visible in Apple's Contacts app. Code:
    guard let contact = contactToAmend.mutableCopy() as? CNMutableContact else { return }
    contact.givenName = "NEW NAME"

    let saveRequest = CNSaveRequest()
    saveRequest.add(contact, toContainerWithIdentifier: store.defaultContainerIdentifier())

    do {
        try store.execute(saveRequest)
        print("Stored ok")
    }
    catch {
        print("Error:\t\(error)")
    }

Looking up this Contact in the Contacts app, I can search for it with the new given name ("NEW NAME"), but the record is then shown with its old (unchanged) name.

It's also worth adding that I am seeing a number of messages / warnings in XCode during runtime:

2023-01-06 14:17:45.628226+0000 [api] Attempt to read notes by an unentitled app
2023-01-06 14:17:54.164223+0000 Metal API Validation Enabled
2023-01-06 14:17:54.436906+0000 [api] Attempt to write notes by an unentitled app
CoreData: warning: Unable to load class named 'ContactsPersistence.CNEWSContactFolder' for entity 'ContactFolder'.  Class not found, using default NSManagedObject instead.
CoreData: warning: Unable to load class named 'ContactsPersistence.CNEWSMapping' for entity 'Mapping'.  Class not found, using default NSManagedObject instead.
2023-01-06 14:17:54.771035+0000 [ABCDContact] An ABCDRecord is being saved without having a container assignment. Assigning the contact to <CNCDContainer 0x600000a89980 ab>. Please remember to assign contacts to containers to avoid recurring container lookup and contact re-validation costs.

What am I missing? What am I doing wrong?

Thanks for any help you can offer!

3      

Have you add Privacy - Contacts Usage Description with a description of why you want to access thier contacts in the info tab?

3      

@mtm  

Hi @NigelGee, yes I have

3      

@mtm  

A partial answer:

To update an existing record, don't use saveRequest.add(contact, toContainerWithIdentifier: store.defaultContainerIdentifier()) but saveRequest.update(contact). I guess that should've been obvious.

By using add, this created a number of (identical) new CNContact records, which I think were presented as one unified contact with the unchanged name

3      

Hacking with Swift is sponsored by Blaze.

SPONSORED Still waiting on your CI build? Speed it up ~3x with Blaze - change one line, pay less, keep your existing GitHub workflows. First 25 HWS readers to use code HACKING at checkout get 50% off the first year. Try it now for free!

Reserve your spot now

Sponsor Hacking with Swift and reach the world's largest Swift community!

Archived topic

This topic has been closed due to inactivity, so you can't reply. Please create a new topic if you need to.

All interactions here are governed by our code of conduct.

 
Unknown user

You are not logged in

Log in or create account
 

Link copied to your pasteboard.