本文主要介紹在ios9.0之后使用Contacts framework讀取通訊錄的方法
- 主要知識(shí)點(diǎn)
- 代碼如下
import UIKit
import Contacts
class ViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
getContatList()
//1.獲取授權(quán)狀態(tài)
let status = CNContactStore.authorizationStatus(for: .contacts)
//2.判斷授權(quán)狀態(tài)锈死,如果未授權(quán),發(fā)起授權(quán)請(qǐng)求
if status == .notDetermined {
let contactStore = CNContactStore()
contactStore.requestAccess(for: .contacts, completionHandler: { (isRight: Bool, nil) in
if isRight {
print("授權(quán)成功")
//遍歷聯(lián)系人列表
self.getContatList()
} else {
print("用戶未授權(quán)")
}
})
}
}
/*
*調(diào)用時(shí)間:
*作用:遍歷通訊錄
*/
private func getContatList() {
//判斷是否有權(quán)讀取通訊錄
let status = CNContactStore.authorizationStatus(for: .contacts)
guard status == .authorized else {
return
}
//1.創(chuàng)建通訊錄對(duì)象
let store = CNContactStore()
//2.定義要獲取的屬性鍵值
let key = [CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey]
//3.獲取請(qǐng)求對(duì)象
let request = CNContactFetchRequest(keysToFetch: key as [CNKeyDescriptor])
//4.遍歷所有聯(lián)系人
do {
try store.enumerateContacts(with: request, usingBlock: { (contact: CNContact, stop: UnsafeMutablePointer<ObjCBool>) in
//4.1獲取姓名
let lastName = contact.familyName
let firstName = contact.givenName
print("姓名:\(lastName)\(firstName)")
//4.2獲取電話號(hào)碼
let phoneNumbers = contact.phoneNumbers
for phoneNumber in phoneNumbers {
print(phoneNumber.label?.characters ?? "")
print(phoneNumber.value.stringValue)
}
})
} catch {
print("讀取通訊錄出錯(cuò)")
}
}
}