獲取通訊錄-AddressBook(swift)
-
導入框架
import AddressBook
-
實現步驟及代碼
override func viewDidLoad() { super.viewDidLoad() // 1. 獲取當前的授權狀態, let status = ABAddressBookGetAuthorizationStatus() if status == .NotDetermined { // 2. 如果當前沒有授權, 應該請求授權 // 參數1: 通訊錄對象 // 參數2: 回調block , 里面包含了請求的結果 let book = ABAddressBookCreate().takeRetainedValue() ABAddressBookRequestAccessWithCompletion(book, { (granted: Bool, error: CFError!) in if granted { print("授權成功") }else { print("授權失敗") } }) } } override func touchesBegan(touches: Set<UITouch>, withEvent event: UIEvent?) { // 0. 驗證授權狀態 let status = ABAddressBookGetAuthorizationStatus() if status != .Authorized { print("沒有權限") return } // 1. 獲取所有的聯系人信息 let book = ABAddressBookCreate().takeRetainedValue() let array = ABAddressBookCopyArrayOfAllPeople(book).takeRetainedValue() // 2. 遍歷每一個聯系人 // CFArray, 遍歷這樣的數組, 應該, 先取出所有的個數, 然后使用響應的函數, 獲取里面每一個元素 let count = CFArrayGetCount(array) for i in 0..<count { // 里面每一個對象, 都是一個聯系人記錄 ABRecord\ // UnsafePointer<Void> == void * : 指向任意對象的指針 // swift 對于這種對象, 有個專門的函數 // 注意事項: 必須明確的恩知道, 目標到底是什么類型 let personP = CFArrayGetValueAtIndex(array, i) let person = unsafeBitCast(personP, ABRecord.self) // 獲取姓名 let firsName = ABRecordCopyValue(person, kABPersonFirstNameProperty).takeRetainedValue() as! String let lastName = ABRecordCopyValue(person, kABPersonLastNameProperty).takeRetainedValue() as! String print(firsName, lastName) // 獲取電話號碼(復雜屬性, 多值) let multiValue = ABRecordCopyValue(person, kABPersonPhoneProperty).takeRetainedValue() as ABMultiValueRef // 遍歷電話號碼 let num = ABMultiValueGetCount(multiValue) for j in 0..<num { // 電話號碼 = 標簽 + 值 let label = ABMultiValueCopyLabelAtIndex(multiValue, j).takeRetainedValue() let value = ABMultiValueCopyValueAtIndex(multiValue, j).takeRetainedValue() as! String print(label, value) } } }