使用联系人框架获取缓慢的联系人
问题描述:
我正在使用Xcode 7.3和Swift 2.2。我试图获取设备的所有联系人并将其存储在一个数组中。它在模拟器上工作正常,但在设备上测试时非常慢(有378个触点)。这需要大约20-25秒。我提出了各种断点,并注意到从手机获取联系人需要最长的时间。用表格视图显示创建的数组中的联系人完全没有时间。这里是我的代码,使用联系人框架获取缓慢的联系人
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")
}
}
这里是我如何填充我的表视图。
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
}
在调试导航器中,CPU也高达98-99%,能量影响非常高。一旦联系人被提取,这些返回到正常值。
原来,提取CNContactPhoneNumbersKey需要这么多时间。只需抓取CNContactGivenNameKey即可(2-3秒)。我们是否有解决方案?
答
框架或代码没有任何问题。我测试了其他设备上的代码,并且它运行良好。它能够在不到一秒的时间内接近900个联系人。
所以问题是设备特定的,重新安装iOS和恢复设备为新的iPhone解决了问题。
如果有其他人面临类似的问题,只需备份您的重要事情(如联系人,照片等),并重新安装iOS并将设备恢复为新的iPhone。
Ouch。看起来不像我期望我的用户做的事! – Randy
这是用户特定的。开发人员可以做什么?但它会计入可怕的用户体验。 –