- 先创建一个CNContactStore对象,用来获取和保存通讯录:
let store = CNContactStore.init() - 判断是否已经授权访问通讯录:
let status:CNAuthorizationStatus = CNContactStore.authorizationStatus(for: .contacts)
if status == .notDetermined {
store.requestAccess(for: .contacts, completionHandler: { (granted:Bool, error:Error?) in
if error != nil{
return
}
if granted {
print("授权访问通讯录")
}
else {
print("拒绝访问通讯录")
}
})
}
- 获取通讯录信息:
// 定义获取属性对应的key值
let keys = [CNContactGivenNameKey,CNContactFamilyNameKey,CNContactPhoneNumbersKey,CNContactImageDataKey]
// 创建CNContactFetchRequest对象
let request = CNContactFetchRequest.init(keysToFetch: keys as [CNKeyDescriptor])
// 遍历通讯录
do {
try store.enumerateContacts(with: request) { (contact:CNContact, stop:UnsafeMutablePointer<ObjCBool>) in
// 获取个人名字
let familyName = contact.familyName
let givenName = contact.givenName
let fullName = String.init(format: "%@ %@", familyName,givenName)
print(fullName)
// 获取电话号码
let phoneNumberArray = contact.phoneNumbers
// 初始化一个数组,存放遍历到的所有电话号码
let contactarray = NSMutableArray()
for i in 0 ..< phoneNumberArray.count {
let phoneNumber = phoneNumberArray[i].value
print(phoneNumber.stringValue)
contactarray.add(phoneNumber.stringValue)
}
// 获取个人头像
var image:UIImage? = nil
if !Utils.isEmpty(contact.imageData) {
let imageData = contact.imageData
image = UIImage.init(data: imageData!)
}
}
} catch {
}
与AddressBook相比,新的Contacts框架更加容易理解和使用,完全可以即刻获取通讯录,并可以进行创建和更新操作,与之相关的开发过程也可以被戏剧般地缩短,能够迅速地完成对通讯录的变更和修改。
网友评论