我正在尝试为我的应用程序删除冗余的 URL。如果一个联系人有多个 URL,这很有效。但如果有链接的联系人,通常保存操作会失败并显示消息“操作无法完成。(CNErrorDomain 错误 2。)”
任何建议如何解决这个问题?统一联系不行吗?如果 URL 的删除应该在单个非统一项目上单独发生,有没有办法从统一项目中获取这些?
这是代码的摘录:
CNSaveRequest *saveRequest = [[CNSaveRequest alloc] init];
NSArray* keys = @[CNContactUrlAddressesKey];
NSPredicate *predicate = [CNContact predicateForContactsWithIdentifiers:identifiers];
NSError *error;
NSArray <CNContact *> *contacts = [_contactStore unifiedContactsMatchingPredicate:predicate keysToFetch:keys error:&error];
for (CNContact *contact in contacts) {
// here we'll collect non-ambigous URLs
NSMutableArray<CNLabeledValue<NSString *> *> *copyOfURLs = [NSMutableArray array];
// just a marker for the moment if a URL with specific prefix was already found
NSString *baseURL = nil;
for (CNLabeledValue<NSString *> *labeledValue in contact.urlAddresses) {
NSString *url = labeledValue.value;
if ([url hasPrefix:APP_IDENTITY_URL_SCHEME]) {
if (baseURL == nil)
baseURL = url;
else
continue;
}
[copyOfURLs addObject:labeledValue];
}
CNMutableContact *updatedContact = [contact mutableCopy];
updatedContact.urlAddresses = copyOfURLs;
[saveRequest updateContact:updatedContact];
}
NSError *saveError;
if (![_contactStore executeSaveRequest:saveRequest error:&saveError]) {
NSLog(@"Saving error: %@", saveError.localizedDescription);
}