Swift 获取联系人信息
如今很多开发者都开始尝试使用Swift进行开发,而且获取手机通讯录作为开发常见的需求
作为一个新的开发者,如果我们开发的应用需求不是特别高,只要求是iOS9以上,
那么恭喜你,基本上你写的很少,
你可以选择Contacts框架,这个框架是在iOS9才出来的@available(iOS 9.0, *)
直接上代码
首先在需要的类中
import Contacts
然后就可以使用这个框架了
首先lazy一个contactStore的对象
lazy var myContactStore: CNContactStore = {
let cn:CNContactStore = CNContactStore()
return cn
}()
首先是检测权限,如果没有授权就要申请权限,有权限则直接获取通讯录,没有权限可以选择弹窗是否需要重新开启权限
func checkContactStoreAuth(){
switch CNContactStore.authorizationStatus(for: .contacts) {
case .notDetermined:
print("未授权")
requestContactStoreAuthorization(myContactStore)
case .authorized:
print("已授权")
readContactsFromContactStore(myContactStore)
case .denied, .restricted:
print("无权限")
//可以选择弹窗到系统设置中去开启
default: break
}
}
请求权限
func requestContactStoreAuthorization(_ contactStore:CNContactStore) {
contactStore.requestAccess(for: .contacts, completionHandler: {[weak self] (granted, error) in
if granted {
print("已授权")
self?.readContactsFromContactStore(contactStore)
}
})
}
读取通讯录
func readContactsFromContactStore(_ contactStore:CNContactStore) {
guard CNContactStore.authorizationStatus(for: .contacts) == .authorized else {
return
}
let keys = [CNContactFamilyNameKey,CNContactGivenNameKey,CNContactPhoneNumbersKey]
let fetch = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])
do {
try contactStore.enumerateContacts(with: fetch, usingBlock: { (contact, stop) in
//姓名
let name = "\(contact.familyName)\(contact.givenName)"
print(name)
//电话
for labeledValue in contact.phoneNumbers {
let phoneNumber = (labeledValue.value as CNPhoneNumber).stringValue
print(phoneNumber)
}
})
} catch let error as NSError {
print(error)
}
}
OK 以上就是iOS9以上的获取方式
对于iOS9以下的话就没有那么方便了
我们只能使用iOS早期的一个AddressBook框架了
一样的 首先import AddressBook
然后加载一个通讯录对象
private lazy var myAddressBook: ABAddressBook = {
var error:Unmanaged?
let ab: ABAddressBook = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()
return ab;
}()
注意这里之所以使用lazy加载,是因为调用ABAddressBookCreateWithOptions进行ABAddressBookCreateWithOptions的初始化需要设置为一个lazy变量,否则在用户拒绝授权的情况下,程序将会崩溃。因为ABAddressBookCreateWithOptions(nil, nil)得到的值为nil
所以这里一定要注意
之后也大致是同样的方式
检测权限
func checkAddressBookAuth() {
switch ABAddressBookGetAuthorizationStatus() {
case .notDetermined:
print("未授权")
requestAddressBookAuthorization(myAddressBook)
case .authorized:
print("已授权")
readContactsFromAddressBook(myAddressBook)
case .denied, .restricted:
print("无权限")
//可以选择弹窗到系统设置中去开启
}
}
申请权限
func requestAddressBookAuthorization(_ addressBook:ABAddressBook) {
ABAddressBookRequestAccessWithCompletion(addressBook, {[weak self] (granted, error) in
if granted {
print("已授权")
self?.readContactsFromAddressBook(addressBook)
}
})
}
读取通讯录
func readContactsFromAddressBook(_ addressBook:ABAddressBook) {
guard ABAddressBookGetAuthorizationStatus() == .authorized else {
return
}
let allContacts = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as Array
for record in allContacts {
let currentContact: ABRecord = record
let name = ABRecordCopyCompositeName(currentContact).takeRetainedValue() as String
print(name)
let currentContactPhones: ABMultiValue = ABRecordCopyValue(currentContact, kABPersonPhoneProperty).takeRetainedValue() as ABMultiValue
for i in 0..
至于如何判断采用哪一个框架
if #available(iOS 9.0, *) {
checkContactStoreAuth()
}else {
checkAddressBookAuth()
}
当然,你还要这样做
需要在info.plist中添加允许访问通讯录的权限,否则iOS10以上的系统也会导致崩溃
OK 至此,通讯录大家应该都能够获取到了
这是我的模拟器运行的结果
附上DEMO地址:https://github.com/spicyShrimp/XLXContact