一.由于iOS8和iOS 9在通讯录上面有语法上的更新所有需要导入不同的依赖库
1.iOS8 导入AddressBookUI 支持代理ABPeoplePickerNavigationControllerDelegate,ABPersonViewControllerDelegate
2.iOS9 导入ContactsUI 支持代理 CNContactPickerDelegate
二.调起通讯录页面
if #available(iOS 9.0, *) {
print("iOS9")
let cncVC = CNContactPickerViewController.init()
cncVC.delegate = self
self.present(cncVC, animated: true, completion: {
})
} else {
print("iOS8")
let cncVC = ABPeoplePickerNavigationController()
cncVC.peoplePickerDelegate = self
self.present(cncVC, animated: true, completion: nil)
}
以上是iOS8和iOS9及以上的分别调发;
下面是各自的代理方法:
/**
调起通讯录相关代码
*/
@available(iOS 9.0, *)
func contactPicker(_ picker: CNContactPickerViewController, didSelect contactProperty: CNContactProperty) {
picker.dismiss(animated: true) {
if contactProperty.key == "phoneNumbers" {
for lab:CNLabeledValue in contactProperty.contact.phoneNumbers {
print(lab.value.stringValue)
var phone = lab.value.stringValue
//对获取的号码进行处理
if lab.value.stringValue.hasPrefix("+") {
let index = lab.value.stringValue.index(lab.value.stringValue.startIndex, offsetBy: 3)
phone = phone.substring(from: index)
}
phone = phone.replacingOccurrences(of: "-", with: "")
phone = phone.replacingOccurrences(of: "(", with: "")
phone = phone.replacingOccurrences(of: ")", with: "")
phone = phone.replacingOccurrences(of: " ", with: "")
print(phone)
}
}else{
print("选择错误")
}
}
}
//找不到为什么如果需要支持iOS8 非得写这个代理方法
@available(iOS 2.0, *)
func personViewController(_ personViewController: ABPersonViewController, shouldPerformDefaultActionForPerson person: ABRecord, property: ABPropertyID, identifier: ABMultiValueIdentifier) -> Bool {
return false
}
//iOS 8选择通讯录处理*
func peoplePickerNavigationController(_ peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord, property: ABPropertyID, identifier: ABMultiValueIdentifier) {
let valueRef = ABRecordCopyValue(person, kABPersonPhoneProperty).takeUnretainedValue() as ABMultiValue
let index:CFIndex = CFIndex(ABMultiValueGetIdentifierAtIndex(valueRef, CFIndex(identifier)))
let phoneValue = ABMultiValueCopyValueAtIndex(valueRef, index)
var phone = phoneValue?.takeUnretainedValue() as! String
if phone.hasPrefix("+") {
let index = phone.index(phone.startIndex, offsetBy: 3)
phone = phone.substring(from: index)
}
phone = phone.replacingOccurrences(of: "-", with: "")
phone = phone.replacingOccurrences(of: "(", with: "")
phone = phone.replacingOccurrences(of: ")", with: "")
phone = phone.replacingOccurrences(of: " ", with: "")
self.dismiss(animated: true) {
print(phone)
}
}
//此方法没有第二层选择,和上面的方法只能二选一
// func peoplePickerNavigationController(_ peoplePicker: ABPeoplePickerNavigationController, didSelectPerson person: ABRecord) {
//
// peoplePicker.dismiss(animated: true) {
// print("111111")
// }
// }