出于某种原因,我不断在我能够使用我的代码访问的许多联系人上获得重复项。有什么理由吗?
var error: Unmanaged<CFError>?
addressBook = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()
if let people = ABAddressBookCopyArrayOfAllPeopleInSourceWithSortOrdering(self.addressBook, nil, ABPersonSortOrdering(kABPersonSortByFirstName)).takeRetainedValue() as? NSArray {
for record in people {
//var contactPerson: ABRecordRef = record
var contactName: String = ABRecordCopyCompositeName(record).takeRetainedValue() as String
var number = ""
var phones: ABMultiValueRef = ABRecordCopyValue(record, kABPersonPhoneProperty).takeRetainedValue()
for j in 0..<ABMultiValueGetCount(phones) {
number = ABMultiValueCopyValueAtIndex(phones, j).takeRetainedValue() as! String
break
}
if (number != "") {
var newPerson = personInfo(name: contactName, number: number)
allContacts.append(newPerson)
}
self.tableView.reloadData()
}
}
答案 0 :(得分:0)
James Richards请使用“联系人”框架而不是使用地址簿。
首先,您应该通过构建阶段添加联系人框架 - >链接二进制文件与库 - >添加(单击+) - &gt;选择联系人框架
import Contacts
然后
let status = CNContactStore.authorizationStatusForEntityType(.Contacts)
if status == .Denied || status == .Restricted {
// user previously denied, so tell them to fix that in settings
return
}
// open it
let store = CNContactStore()
store.requestAccessForEntityType(.Contacts) { granted, error in
guard granted else {
dispatch_async(dispatch_get_main_queue()) {
// user didn't grant authorization, so tell them to fix that in settings
print(error)
}
return
}
// get the contacts
var contacts = [CNContact]()
let request = CNContactFetchRequest(keysToFetch:[CNContactIdentifierKey, CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)])
do {
try store.enumerateContactsWithFetchRequest(request) { contact, stop in
contacts.append(contact)
}
}
catch {
print(error)
}
// do something with the contacts array (e.g. print the names)
let formatter = CNContactFormatter()
formatter.style = .FullName
for contact in contacts {
print(formatter.stringFromContact(contact))
}
}
输出结果
Optional("John Appleseed")
Optional("Kate Bell")
Optional("Anna Haro")
Optional("Daniel Higgins Jr.")
Optional("David Taylor")
Optional("Hank M. Zakroff")