import SwiftyJSON
let store = CNContactStore()
store.requestAccess(for: .contacts, completionHandler: {
granted, error in
guard granted else {
let alert = UIAlertController(title: “Can’t access contact”, message: “Please go to Settings -> MyApp to enable contact permission”, preferredStyle: .alert)
alert.addAction(UIAlertAction(title: “OK”, style: .default, handler: nil))
self.present(alert, animated: true, completion: nil)
return
}
let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactPhoneNumbersKey] as [Any]
let request = CNContactFetchRequest(keysToFetch: keysToFetch as! [CNKeyDescriptor])
var cnContacts = [CNContact]()
do {
try store.enumerateContacts(with: request){
(contact, cursor) -> Void in
cnContacts.append(contact)
}
} catch let error {
NSLog(“Fetch contact error: \(error)”)
}
NSLog(“>>>> Contact list:”)
for contact in cnContacts {
print(contact)
var dictionaryPhoneNumberTemp = [String:[String]]()
print(contact.phoneNumbers)
let fullName = CNContactFormatter.string(from: contact, style: .fullName) ?? “No Name”
NSLog(“\(fullName): \(contact.phoneNumbers.description)”)
var arrayPhoneNumberTemp = [String]()
for cNLabelValue in contact.phoneNumbers {
var phone = String()
phone = cNLabelValue.value.stringValue
if (phone != “”) {
arrayPhoneNumberTemp.append(phone)
}
}
dictionaryPhoneNumberTemp[fullName] = arrayPhoneNumberTemp
// for (CNLabeledValue *label in contact.phoneNumbers) {
// phone = [label.value stringValue];
// if ([phone length] > 0) {
// [contactNumbersArray addObject:phone];
// }
// }
self.arrayContacts.append(dictionaryPhoneNumberTemp)
}
print(self.arrayContacts)
let jSONTemp = JSON(self.arrayContacts)
print(jSONTemp)