I'm trying to insert into var contacts: [CNContact] = []
the var store = CNContactStore() but I did not find the right code for this job, i found this function that I need to give that a name
func findContactsWithName(name: String) {
AppDelegate.sharedDelegate().checkAccessStatus({ (accessGranted) -> Void in
if accessGranted {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
do {
let predicate: NSPredicate = CNContact.predicateForContactsMatchingName(name)
let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactBirthdayKey, CNContactViewController.descriptorForRequiredKeys()]
self.contacts = try self.store.unifiedContactsMatchingPredicate(predicate, keysToFetch:keysToFetch)
self.tableView.reloadData()
}
catch {
print("Unable to refetch the selected contact.")
}
})
}
})
}
I want to insert self.contacts all the records and not only one with name equal
/// The default key descriptors to fetch
public var defaultFetchKeys: [String] = [CNContactGivenNameKey,
CNContactFamilyNameKey,
CNContactPhoneNumbersKey,
CNContactImageDataAvailableKey,
CNContactThumbnailImageDataKey]
/**
Fetch contacts from the user's device
- parameter sortOrder: The sort order that should be used. Default none.
- returns: A list of contacts
*/
public func fetchContacts(withSortOrder sortOrder: CNContactSortOrder = .givenName,
qos: DispatchQoS.QoSClass = .background) -> Promise<[Contact]>
{
return Promise { seal in
DispatchQueue.global(qos: qos).async {
let store = CNContactStore()
var contacts = [Contact]()
/// A `PhoneNumberKit` object used to parse and format numbers (expensive!)
let phoneNumberKit = PhoneNumberKit()
let request = CNContactFetchRequest(keysToFetch: self.defaultFetchKeys as [CNKeyDescriptor])
request.sortOrder = sortOrder
request.unifyResults = true
do {
try store.enumerateContacts(with: request) { contact, _ in
if let user = Contact(contact: contact, kit: phoneNumberKit) {
contacts.append(user)
}
}
DispatchQueue.main.async {
seal.fulfill(contacts)
}
} catch {
DispatchQueue.main.async {
seal.reject(error)
}
}
}
}
}
I am also using PhoneNumberKit to standardise all numbers and PromiseKit, to chain my requests, but you can pretty much adjust it whatever you want it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With