我正在访问所有包含姓名和电话号码的联系人。我在单个 CNContact 中获得了包含多个电话号码的 CNContact 数组,这是预期的。
func fetchContacts() {
let store = CNContactStore()
let keysToFetch = [
CNContactFormatter.descriptorForRequiredKeys(for: .fullName),
CNContactPhoneNumbersKey as any CNKeyDescriptor
]
let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)
var result: [CNContact] = []
do {
try store.enumerateContacts(with: fetchRequest) { contact, stop in
if contact.phoneNumbers.count > 0 {
result.append(contact)
}
}
print(result)
} catch let error {
print("Fetching contacts failed: \(error)")
}
}
输出:
[
Contact(fullName : "John Appleseed", phoneNumbers: ["888-555-5512", "888-555-1212"]),
Contact(fullName : "Kate Bell", phoneNumbers: ["(555) 564-8583", "(415) 555-3695"])
]
但我想要实现的是具有单个电话号码的 CNContact 数组。
[
Contact(fullName : "John Appleseed", phoneNumber: "888-555-5512"),
Contact(fullName : "John Appleseed", phoneNumber: "888-555-1212"),
Contact(fullName : "Kate Bell", phoneNumber: "(555) 564-8583"),
Contact(fullName : "Kate Bell", phoneNumber: "(415) 555-3695")
]
在这种情况下,什么 NSPrediction 会起作用?
注意:忽略UI错误,已经实现的权限,希望在读取联系人之前(获取请求)而不是在读取联系人之后实现。
如果您想要自定义输出格式,您将需要自定义类型
比如说
struct Contact {
let name: String
let phoneNumber: String
}
然后在循环中转换为该类型
var resultContact: [Contact] = []
do {
try store.enumerateContacts(with: fetchRequest) { contact, stop in
if contact.phoneNumbers.count > 0 {
contact.phoneNumbers.forEach { phoneNumber in
let phoneNumber = phoneNumber.value.stringValue
resultContact.append(Contact(name: contact.givenName + " " + contact.familyName, phoneNumber: phoneNumber))
}
}
}
print(resultContact)
} catch let error {
print("Fetching contacts failed: \(error)")
}