如何解决CNContactStore:删除和插入大量联系人时出错
我正在实现从备份中恢复联系人的功能。我遇到了大量联系人 (> 1000) 的问题,通常 try store.execute (saveRequest)
会出错。
private func recoveryContacts(_ contacts: [CNContacts],completion: ((Result<Bool,Error>) -> Void)?) {
var availableRecoveryAttempt = 3
var fetchedContacts = contactFetcher.fetch()
repeat {
deleteallContacts()
saveContacts(contacts)
availableRecoveryAttempt -= 1
fetchedContacts = contactFetcher.fetch()
} while (fetchedContacts.count != contacts.count) && (availableRecoveryAttempt != 0)
completion?(.success(fetchedContacts.count == contacts.count))
}
private func deleteallContacts() {
let saveRequest = CNSaveRequest()
var contacts = contactFetcher.fetch()
contacts
.compactMap { $0.mutablecopy() as? CNMutableContact }
.forEach { saveRequest.delete($0) }
do {
try store.execute(saveRequest)
} catch {
print(error)
}
}
private func saveContacts(_ contacts: [CNContact]) {
let saveRequest = CNSaveRequest()
let containerId = store.defaultContainerIdentifier()
contacts
.compactMap { $0.mutablecopy() as? CNMutableContact }
.forEach { saveRequest.add($0,toContainerWithIdentifier: containerId) }
do {
try store.execute(saveRequest) // this generate error
} catch {
print(error)
}
}
错误:
Error Domain=CNErrorDomain Code=1 "Communication Error" UserInfo={NSLocalizedDescription=Communication Error,NSLocalizedFailureReason=An error occurred while trying to communicate with the Contacts service.}
//和
Error Domain=CNErrorDomain Code=2 "(null)"
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。