class Contact {
static func auth() -> Bool {
let status = CNContactStore.authorizationStatus(for: .contacts)
return status != .authorized
}
/// 获取通讯录列表
/// - Returns: 返回通讯录数组
static func getList() -> [[String : Any]] {
let store = CNContactStore()
var keysToFetch: [CNKeyDescriptor] = [
CNContactFamilyNameKey as CNKeyDescriptor,
CNContactGivenNameKey as CNKeyDescriptor,
CNContactNicknameKey as CNKeyDescriptor,
CNContactOrganizationNameKey as CNKeyDescriptor,
CNContactJobTitleKey as CNKeyDescriptor,
CNContactDepartmentNameKey as CNKeyDescriptor,
CNContactBirthdayKey as CNKeyDescriptor,
CNContactNonGregorianBirthdayKey as CNKeyDescriptor,
CNContactDatesKey as CNKeyDescriptor,
CNContactTypeKey as CNKeyDescriptor,
CNContactPhoneNumbersKey as CNKeyDescriptor,
CNContactEmailAddressesKey as CNKeyDescriptor,
CNContactPostalAddressesKey as CNKeyDescriptor,
CNContactInstantMessageAddressesKey as CNKeyDescriptor,
CNContactSocialProfilesKey as CNKeyDescriptor,
CNContactUrlAddressesKey as CNKeyDescriptor,
]
if #available(iOS 13.0, *) {
} else {
keysToFetch.append(CNContactNoteKey as CNKeyDescriptor)
}
let request = CNContactFetchRequest(keysToFetch: keysToFetch)
var contactArr = [[String : Any]]()
do {
try store.enumerateContacts(with: request) { contact, stop in
let name = "\(contact.familyName)\(contact.givenName)"
var note = ""
var dateStr = ""
if contact.isKeyAvailable(note) {
note = contact.note
}
for cnDate in contact.dates {
if let date = cnDate.value.date {
let label = CNLabeledValue<NSString>.localizedString(forLabel: cnDate.label ?? "")
if !label.isEmpty {
dateStr = "\(Int(date.timeIntervalSince1970) * 1000)"
}
}
}
var email = ""
if !contact.emailAddresses.isEmpty {
email = contact.emailAddresses[0].value as String
}
for phoneNumber in contact.phoneNumbers {
contactArr.append([
"id": "",
"description": "",
"formattedNumber": "",
"lastCallTime": "",
"callCount": "",
"totalCallDuration": "",
"telephoneNo": phoneNumber.value.stringValue,
"type": contact.contactType.rawValue,
"note": note,
"emailAddress": email,
"job": contact.jobTitle,
"name": name.isEmpty ? "" : name,
"nickname": contact.nickname,
"creationData": dateStr,
"modificationDate": "",
"department": contact.departmentName,
"organization": contact.organizationName
])
}
}
return contactArr
} catch {
print("Error fetching contacts: \(error)")
}
return []
}
}
网友评论