当我运行以下代码时,我在最后一个try语句中收到此错误:
错误域= CNErrorDomain代码= 200“更新的记录不存在” UserInfo = {NSLocalizedFailureReason =保存请求失败,因为它 更新不存在或已被删除的记录。 CNInvalidRecords =( “”),NSLocalizedDescription =更新记录不 存在}
我不明白这个错误。如你所见,CNGroup的记录显然存在,因为我刚创建它没有错误。我还检查了模拟器。联系人和小组都存在。
let store = CNContactStore()
let defaultContainerIdentifier = store.defaultContainerIdentifier()
let cnMutableGroup = CNMutableGroup()
cnMutableGroup.name = "Temple5"
let groupIdentifier = cnMutableGroup.identifier
let cnMutableContact = CNMutableContact()
cnMutableContact.familyName = "Ralph5"
cnMutableContact.givenName = "Rolfson5"
let contactIdentifier = cnMutableContact.identifier
let saveRequest = CNSaveRequest()
saveRequest.add(cnMutableGroup, toContainerWithIdentifier: defaultContainerIdentifier)
saveRequest.add(cnMutableContact, toContainerWithIdentifier: defaultContainerIdentifier)
do {
try store.execute(saveRequest)
} catch let error as NSError {
print(error)
}
let predicateGroups = CNGroup.predicateForGroups(withIdentifiers: [groupIdentifier])
var cnGroups: [CNGroup] = []
do {
cnGroups = try store.groups(matching: predicateGroups)
} catch let error as NSError {
print(error)
}
let cnGroup = cnGroups.first!
let predicateContacts = CNContact.predicateForContacts(withIdentifiers: [contactIdentifier])
let keys = [CNContactGivenNameKey, CNContactPhoneNumbersKey]
var cnContacts: [CNContact] = []
do {
cnContacts = try store.unifiedContacts(matching: predicateContacts, keysToFetch: keys as [CNKeyDescriptor])
} catch let error as NSError {
print(error)
}
let cnContact = cnContacts.first!
saveRequest.addMember(cnContact, to: cnGroup)
do {
try store.execute(saveRequest)
} catch let error as NSError {
print(error)
}
答案 0 :(得分:0)
尝试传递nil作为容器标识符。
saveRequest.add(cnMutableContact, toContainerWithIdentifier: nil)