本文只作自用笔记,不喜忽喷,诚谢纠错。

1、系统通讯录的调用。这个比较简单,就是调用系统的UI,然后遵守CNContactPickerDelegate协议,里面有选中当前cell以及一些其他按钮的被点击触发的回调。

代码:

  (1)调用系统控制器CNContactPickerViewController

     let picker = CNContactPickerViewController()

     picker.delegate = self //遵守CNContactPickerDelegate协议

      self.present(picker, animated: true, completion: nil)

  (2)实现协议方法,这里只写选中时调用的方法,还有一些比如取消按钮的回调,都在CNContactPickerDelegate协议里面

    

    //实现CNContactPickerDelegate代理方法--可获得姓名,电话,邮箱等信息,所有可获取参数都在CNContact类中,具体Commond进去详查。

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {

        print(contact.familyName) //

        print(contact.givenName) //

        print(contact.phoneNumbers)//这里是电话号码的数组

        for i in contact.phoneNumbers {

            let phoneNum = i.value.stringValue //电话号码

            print(phoneNum)

        }

    }

2.自定义通讯录

其实所谓自定义,就是我们需要拿到所有的通讯录数据然后进行重新布局。所以这里只贴出获取通讯录信息的类,这里摘自:http://www.hangge.com/blog/cache/detail_1523.html通信录获取联系人。只是对其代码中出现nil时作了一个简单的判断。直接贴代码吧。哦,这里还有一点,需要在info.plist文件里面设置通讯录访问权限。

import UIKit

import Contacts

class SelfAddressBook: UIViewController {

    

    override func viewDidLoad() {

        super.viewDidLoad()

        CNContactStore().requestAccess(for: .contacts) { (isRight, error) in

            if isRight {

                //授权成功加载数据。

                self.loadContactsData()

            }

        }

    }

    

    func loadContactsData() {

        //获取授权状态

        let status = CNContactStore.authorizationStatus(for: .contacts)

        //判断当前授权状态

        guard status == .authorized else { return }

        

        //创建通讯录对象

        let store = CNContactStore()

        

        //获取Fetch,并且指定要获取联系人中的什么属性

        let keys = [CNContactFamilyNameKey, CNContactGivenNameKey, CNContactNicknameKey,

                    CNContactOrganizationNameKey, CNContactJobTitleKey,

                    CNContactDepartmentNameKey, CNContactNoteKey, CNContactPhoneNumbersKey,

                    CNContactEmailAddressesKey, CNContactPostalAddressesKey,

                    CNContactDatesKey, CNContactInstantMessageAddressesKey

        ]

        

        //创建请求对象,需要传入一个(keysToFetch: [CNKeyDescriptor]) 包含'CNKeyDescriptor'类型的数组

        let request = CNContactFetchRequest(keysToFetch: keys as [CNKeyDescriptor])

        

        //遍历所有联系人

        do {

            try store.enumerateContacts(with: request, usingBlock: {

                (contact : CNContact, stop : UnsafeMutablePointer<ObjCBool>) -> Void in

                

                //获取姓名

                let lastName = contact.familyName

                let firstName = contact.givenName

                print("姓名:\(lastName)\(firstName)")

                

                //获取昵称

                let nikeName = contact.nickname

                print("昵称:\(nikeName)")

                

                //获取公司(组织)

                let organization = contact.organizationName

                print("公司(组织):\(organization)")

                

                //获取职位

                let jobTitle = contact.jobTitle

                print("职位:\(jobTitle)")

                

                //获取部门

                let department = contact.departmentName

                print("部门:\(department)")

                

                //获取备注

                let note = contact.note

                print("备注:\(note)")

                

                //获取电话号码

                print("电话:")

                for phone in contact.phoneNumbers {

                    //获得标签名(转为能看得懂的本地标签名,比如workhome

                    if phone.label != nil{

                        let label = CNLabeledValue<NSString>.localizedString(forLabel: phone.label!)

                        //获取号码

                        let value = phone.value.stringValue

                        print("\t\(label)\(value)")

                    }

                }

                

                //获取Email

                print("Email")

                for email in contact.emailAddresses {

                    if email.label != nil{

                        //获得标签名(转为能看得懂的本地标签名)

                        let label = CNLabeledValue<NSString>.localizedString(forLabel: email.label!)

                        //获取值

                        let value = email.value

                        print("\t\(label)\(value)")

                    }

                }

                

                //获取地址

                print("地址:")

                for address in contact.postalAddresses {

                    if address.label != nil{

                        //获得标签名(转为能看得懂的本地标签名)

                        let label = CNLabeledValue<NSString>.localizedString(forLabel: address.label!)

                        //获取值

                        let detail = address.value

                        let contry = detail.value(forKey: CNPostalAddressCountryKey) ?? ""

                        let state = detail.value(forKey: CNPostalAddressStateKey) ?? ""

                        let city = detail.value(forKey: CNPostalAddressCityKey) ?? ""

                        let street = detail.value(forKey: CNPostalAddressStreetKey) ?? ""

                        let code = detail.value(forKey: CNPostalAddressPostalCodeKey) ?? ""

                        let str = "国家:\(contry) :\(state) 城市:\(city) 街道:\(street) 邮编:\(code)"

                        print("\t\(label)\(str)")

                    }

                }

                

                //获取纪念日

                print("纪念日:")

                for date in contact.dates {

                    if date.label != nil{

                        //获得标签名(转为能看得懂的本地标签名)

                        let label = CNLabeledValue<NSString>.localizedString(forLabel: date.label!)

                        //获取值

                        let dateComponents = date.value as DateComponents

                        let value = NSCalendar.current.date(from: dateComponents)

                        let dateFormatter = DateFormatter()

                        dateFormatter.dateFormat = "yyyyMMdd HH:mm:ss"

                        print("\t\(label)\(dateFormatter.string(from: value!))")

                    }

                }

                

                //获取即时通讯(IM)

                print("即时通讯(IM)")

                for im in contact.instantMessageAddresses {

                    if im.label != nil{

                        //获得标签名(转为能看得懂的本地标签名)

                        let label = CNLabeledValue<NSString>.localizedString(forLabel: im.label!)

                        //获取值

                        let detail = im.value

                        let username = detail.value(forKey: CNInstantMessageAddressUsernameKey) ?? ""

                        let service = detail.value(forKey: CNInstantMessageAddressServiceKey) ?? ""

                        print("\t\(label)\(username) 服务:\(service)")

                    }

                }

                

                print("----------------")

                

            })

        } catch {

            print(error)

        }

    }

    

    override func didReceiveMemoryWarning() {

        super.didReceiveMemoryWarning()

    }

}