Apple itself offers a nice piece of code for adding own addresses to "Contacts"-App. (see documentation for "Contacts" - Listing 1 Creating a contact)
I try to use this code. But when executing this, my app crashes with error on saving the data. (see image)
My code so far:
import AppKit
import Contacts
class ContactsClass {
func addToContacts(
lastName: String,
firstName: String,
birthDate: Date?,
mail: String = "",
phone1: String = "",
phone2: String = "",
mobile: String = "",
street: String,
city: String,
postCode: String
) {
// Create a mutable object to add to the contact
let contact = CNMutableContact()
contact.givenName = firstName
contact.familyName = lastName
if mail != "" {
let homeEmail = CNLabeledValue(label: CNLabelHome, value: mail as NSString)
contact.emailAddresses = [homeEmail]
}
contact.phoneNumbers = []
if phone1 != "" {
contact.phoneNumbers.append(CNLabeledValue(label: CNLabelPhoneNumberMain, value: CNPhoneNumber(stringValue: phone1)))
}
if phone2 != "" {
contact.phoneNumbers.append(CNLabeledValue(label: CNLabelPhoneNumberMain, value: CNPhoneNumber(stringValue: phone2)))
}
if mobile != "" {
contact.phoneNumbers.append(CNLabeledValue(label: CNLabelPhoneNumberMobile, value: CNPhoneNumber(stringValue: mobile)))
}
let homeAddress = CNMutablePostalAddress()
homeAddress.street = street
homeAddress.city = city
homeAddress.postalCode = postCode
contact.postalAddresses = [CNLabeledValue(label: CNLabelHome, value: homeAddress)]
if birthDate != nil {
let calendar = Calendar.current
let dateComponents = calendar.dateComponents([.year,.month,.day], from: birthDate!)
var birthday = DateComponents()
birthday.day = dateComponents.day
birthday.month = dateComponents.month
birthday.year = dateComponents.year // (Optional) Omit the year value for a yearless birthday
contact.birthday = birthday
}
// Save the newly created contact
let store = CNContactStore()
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier: nil)
do {
try store.execute(saveRequest) // <<-- Error appears here!!
} catch {
print("Saving contact failed, error: \(error)")
// Handle the error
}
}
}
Console errors are:
2022-10-28 06:26:03.473439+0200 justCare[11808:992463] [api] Attempt to write notes by a pre-Fall-2022 app
2022-10-28 06:26:03.499714+0200 justCare[11808:992463] [plugin] CDX_AB_GetGroupCollectionPath: nil group
2022-10-28 06:26:03.499770+0200 justCare[11808:992463] [plugin] CDX_AB_GetGroupCollectionPath: nil group
2022-10-28 06:26:03.500823+0200 justCare[11808:992463] [ABCDContact] An ABCDRecord is being saved without having a container assignment. Assigning the contact to <CNCDContainer 0x600001f9bba0 ab>. Please remember to assign contacts to containers to avoid recurring container lookup and contact re-validation costs.
Access to Contatcs is granted. Sandboxing is properly set for Contacts. So why this error now?
Environment:
- macOS Ventura
- XCODE 14.0.1