In my application I create a CNContact and save to the contacts store, I also save the contact's identifier. In another section of the app I use the identifier to fetch that contact but is not working in iOS 13. (This does works on iOS 12)
Note: I am aware of the contact note key permission on iOS 13, but I am not fetching that field.
Here is how I create the contact:
func createPlaceholderContactFor(telephoneNumber: String) {
guard
placeholderContactIdentifier == nil,
CNContactStore.authorizationStatus(for: .contacts) == .authorized
else {
return
}
// Creating a mutable object to add to the contact
let contact = CNMutableContact()
contact.imageData = UIImage(named: "MainIcon")?.jpegData(compressionQuality: 1.0)
contact.givenName = placeholderDefaultName
contact.familyName = ""
contact.phoneNumbers = [CNLabeledValue(
label:CNLabelPhoneNumberiPhone,
value:CNPhoneNumber(stringValue:telephoneNumber))]
// Saving the newly created contact
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier:nil)
do {
let store = CNContactStore()
try store.execute(saveRequest)
if contact.isKeyAvailable(CNContactIdentifierKey) {
print(contact.identifier) //this is printed on console and contact appears on phone app.
placeholderContactIdentifier = contact.identifier
}
} catch {
print(error.localizedDescription)
}
}
This is how I fetch the contact:
private func placeholderContact() -> CNContact? {
guard
let identifier = placeholderContactIdentifier,
CNContactStore.authorizationStatus(for: .contacts) == .authorized
else { return nil }
let predicate: NSPredicate = CNContact.predicateForContacts(withIdentifiers: [identifier])
let keysToFetch = [
CNContactIdentifierKey as CNKeyDescriptor,
CNContactGivenNameKey as CNKeyDescriptor,
CNContactFamilyNameKey as CNKeyDescriptor,
CNContactPhoneNumbersKey as CNKeyDescriptor
]
do {
let store = CNContactStore()
let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keysToFetch)
return contacts.first
}
catch {
print(error.localizedDescription)
return nil
}
}
I also tried using let contact = try store.unifiedContact(withIdentifier: identifier, keysToFetch: keysToFetch) instead of let contacts = try store.unifiedContacts(matching: predicate, keysToFetch: keysToFetch) but this throws an error.