-2

有没有一种方法可以使用没有属性的联系人框架来获取联系人?

例子:

myContactArray = unifiedContactsNotCalled("John")

PS:我知道那行与真正的代码完全不同,它只是用于说明目的的服务建议

4

1 回答 1

3

在我概述如何找到不匹配的名称之前,让我们回顾一下如何找到匹配的名称。简而言之,您将使用谓词:

let predicate = CNContact.predicateForContacts(matchingName: searchString)
let matches = try store.unifiedContacts(matching: predicate, keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])    // use whatever keys you want

(显然,您可以将其包装在一个do--构造或任何您想要的错误处理模式中。trycatch

不幸的是,您不能在 Contacts 框架中使用自己的自定义谓词,而只能使用CNContact预定义的谓词。因此,如果您想查找姓名不包含“John”的联系人,您必须手动enumerateContacts(with:)构建结果:

let formatter = CNContactFormatter()
formatter.style = .fullName

let request = CNContactFetchRequest(keysToFetch: [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])   // include whatever other keys you may need

// find those contacts that do not contain the search string

var matches = [CNContact]()
try store.enumerateContacts(with: request) { contact, stop in
    if !(formatter.string(from: contact)?.localizedCaseInsensitiveContains(searchString) ?? false) {
        matches.append(contact)
    }
}
于 2017-03-12T16:05:52.640 回答