Reputation: 2066
I am using Xcode 7.3 and Swift 2.2. I am trying to fetch all the contacts of the device and store it in an array. It works fine on simulator but is very slow when tested on device(with 378 contacts). It takes about 20-25 seconds to do so. I put various breakpoints and noticed that fetching contacts from the phone takes the maximum time. Displaying the contacts from the created array with a table view takes no time at all. Here is my code,
var results: [CNContact] = []
func retrieveContactsWithStore() {
let contactStore = CNContactStore()
var i = 0
var allContainers: [CNContainer] = []
do {
allContainers = try contactStore.containersMatchingPredicate(nil)
} catch {
print("Error fetching containers")
}
for container in allContainers {
let fetchPredicate = CNContact.predicateForContactsInContainerWithIdentifier(container.identifier)
do {
let containerResults = try contactStore.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: [
CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey])
results.appendContentsOf(containerResults)
} catch {
print("Error fetching results for container")
}
}
And here's how I am populating my table view.
override func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("Cell", forIndexPath: indexPath)
cell.textLabel?.text = results[indexPath.row].givenName
cell.detailTextLabel?.text = ((results[indexPath.row].phoneNumbers[0].value as? CNPhoneNumber)?.valueForKey("digits") as? String)
return cell
}
In the Debug Navigator too the CPU spikes to 98-99%, Energy Impact - Very High. These return to normal values once the contacts have been fetched.
Turns out that fetching CNContactPhoneNumbersKey takes so much time. Just fetching CNContactGivenNameKey is quick.(2-3 secs). Do we have a solution for this?
Upvotes: 3
Views: 1325
Reputation: 2066
There is nothing wrong with the Framework or the code. I tested the code on other devices and there it worked fine. It was able to fetch close to 900 contacts in less than a second.
So the problem was device specific and reinstalling iOS and restoring the device as new iPhone solved the issue.
If anyone else faces similar issue, just backup your important things (e.g.- contacts, photos etc.) and reinstall iOS and restore device as new iPhone.
Upvotes: 1