用于CNContactFormatter
构建显示名称。为请求指定键时,请使用descriptorForRequiredKeysForStyle
以确保您请求了适当的字段。
在 Swift 中,它将是:
let store = CNContactStore()
store.requestAccess(for: .contacts) { granted, error in
guard granted else {
print(error?.localizedDescription ?? "Unknown error")
return
}
let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey as CNKeyDescriptor, CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])
let formatter = CNContactFormatter()
formatter.style = .fullName
do {
try store.enumerateContacts(with: request) { contact, stop in
if let name = formatter.string(from: contact) {
print(name)
}
}
} catch let fetchError {
print(fetchError)
}
}
您建议您遇到既没有姓名也没有公司,只有电话号码的情况。那么,您必须自己手动处理:
let request = CNContactFetchRequest(keysToFetch: [CNContactIdentifierKey as CNKeyDescriptor, CNContactPhoneNumbersKey as CNKeyDescriptor, CNContactFormatter.descriptorForRequiredKeys(for: .fullName)])
do {
try store.enumerateContacts(with: request) { contact, stop in
if let name = formatter.string(from: contact) {
print(name)
} else if let firstPhone = contact.phoneNumbers.first?.value {
print(firstPhone.stringValue)
} else {
print("no name; no number")
}
}
} catch let fetchError {
print(fetchError)
}
对于 Swift 2,请参阅此答案的先前版本。