获取通讯录-ContactsUI(swift)

获取通讯录-ContactsUI(swift)

  1. 导入框架

    import ContactsUI
    
  2. 实现步骤及代码

    override func touchesBegan(touches: Set, withEvent event: UIEvent?) {
    
    if #available(iOS 9.0, *) {
        // 1. 创建联系人选择控制器啊
        let vc = CNContactPickerViewController()
    
        // 1.1 设置代理, 接收用户的点击
        vc.delegate = self
    
        // 2. 弹出控制器
        presentViewController(vc, animated: true, completion: nil)
    } else {
        // Fallback on earlier versions
    }
    

}

// MARK: - CNContactPickerDelegate
extension ViewController: CNContactPickerDelegate {

    // 取消选中时调用
    func contactPickerDidCancel(picker: CNContactPickerViewController) {
        print("取消")
    }

    // 选择某个联系人
    func contactPicker(picker: CNContactPickerViewController, didSelectContact contact: CNContact) {

    }

    // 选择某个联系人 某个属性
    //
    func contactPicker(picker: CNContactPickerViewController, didSelectContactProperty contactProperty: CNContactProperty) {

    }

    // 选择多个联系人
    func contactPicker(picker: CNContactPickerViewController, didSelectContacts contacts: [CNContact]) {

        for contact in contacts {
            let name = contact.familyName
            print(name)

            let phones = contact.phoneNumbers
            for phone in phones {

                let label = phone.label
                let value = phone.value as! CNPhoneNumber
                print(label, value.stringValue)

            }
        }
    }
    //    // 选择一个联系人多个属性
    //    func contactPicker(picker: CNContactPickerViewController, didSelectContactProperties contactProperties: [CNContactProperty]) {
    //
    //    }
```

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