获取通讯录-AddressBook(swift)

获取通讯录-AddressBook(swift)

  1. 导入框架

    import AddressBook
    
  2. 实现步骤及代码

    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, 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.. == 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..

你可能感兴趣的:(获取通讯录-AddressBook(swift))