CNContactStore executeSaveRequest 失败,CNErrorDomain 代码=101 没有可访问的可写容器

CNContactStore executeSaveRequest fails with CNErrorDomain Code=101 No Accessible Writable Containers

我添加了一段代码,用户点击一个按钮即可保存联系人,但现在我的代码无法正常工作,并且在执行 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)
        })
}

应保存联系人而不是错误,因为 "Error Domain=CNErrorDomain Code=101 "没有可访问的可写容器" UserInfo={NSLocalizedDescription=没有可访问的可写容器,NSLocalizedFailureReason=此应用程序无权访问任何可写的联系人容器。}"。 =11=]

您是否在物理设备上的模拟器上进行测试?

您正在使用托管设备(通过企业帐户)吗?

从 iOS 11.3 开始苹果声明:

Mobile Device Management
New Features

        Prevent unmanaged apps from accessing contacts in managed accounts. 

Link 这里 https://developer.apple.com/library/archive/releasenotes/General/RN-iOS-11.3/index.html

除此之外,我觉得你的代码还不错。