Я добавил код, в котором пользователь нажимает кнопку, и контакт будет сохранен, но сейчас мой код не работает, и он не работает во время выполнения объекта saveRequest.
private func checkContactsAccess(_ completionHandler: @escaping () -> Void) {
switch CNContactStore.authorizationStatus(for: .contacts) {
// Update our UI if the user has granted access to their Contacts
case .authorized:
completionHandler()
// Prompt the user for access to Contacts if there is no definitive answer
case .notDetermined :
CNContactStore().requestAccess(for: .contacts) {granted, error in
if granted {
DispatchQueue.main.async {
completionHandler()
}
} else {
print("not allowed")
}
}
// Display a message if the user has denied or restricted access to Contacts
case .denied,
.restricted:
let alert = UIAlertController(title: "Privacy Warning!",
message: "Permission was not granted for Contacts.",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
}
}
// This method is called when the user has granted access to their address book data.
private func accessGrantedForContacts() {
checkContactsAccess ({
// Creating a mutable object to add to the contact
let contact = CNMutableContact()
contact.givenName = "John"
contact.familyName = "Appleseed"
contact.phoneNumbers = [CNLabeledValue(
label:CNLabelPhoneNumberiPhone,
value:CNPhoneNumber(stringValue:"(408) 555-0126"))]
let homeAddress = CNMutablePostalAddress()
homeAddress.street = "1 Infinite Loop"
homeAddress.city = "Cupertino"
homeAddress.state = "CA"
homeAddress.postalCode = "95014"
contact.postalAddresses = [CNLabeledValue(label:CNLabelHome, value:homeAddress)]
let birthday = NSDateComponents()
birthday.day = 1
birthday.month = 4
birthday.year = 1988 // You can omit the year value for a yearless birthday
contact.birthday = birthday as DateComponents
// Saving the newly created contact
let store = CNContactStore()
let saveRequest = CNSaveRequest()
saveRequest.add(contact, toContainerWithIdentifier:nil)
print(saveRequest)
do {
try store.execute(saveRequest)
} catch {
print(error)
}
print("Done")
let alert = UIAlertController(title: "Saved",
message: "Saved",
preferredStyle: .alert)
alert.addAction(UIAlertAction(title: "OK", style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
})
}
Контакт должен быть сохранен вместо ошибки как "Ошибка домена = код CNErrorDomain = 101" Нет доступных для записи контейнеров "UserInfo = {NSLocalizedDescription = Нет доступных для записи контейнеров, NSLocalizedFailureReason = Это приложение не имеет доступа к любым доступным для записи контейнерам контактов.} «