I am struggling to understand managing Contacts via Swift on macOS. Any help with the two items below would be much appreciated.
- 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)")
}
- 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!