iOS - Swift

swift-获取通讯录iOS9.0(Contacts frame

2017-02-13  本文已影响169人  figure_ai

本文主要介绍在ios9.0之后使用Contacts framework读取通讯录的方法

import UIKit
import Contacts
class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        getContatList()
        //1.获取授权状态
        let status = CNContactStore.authorizationStatus(for: .contacts)
        //2.判断授权状态,如果未授权,发起授权请求
        if status == .notDetermined {
            let contactStore = CNContactStore()
            contactStore.requestAccess(for: .contacts, completionHandler: { (isRight: Bool, nil) in
                if isRight {
                    print("授权成功")
                    //遍历联系人列表
                    self.getContatList()
                } else {
                    print("用户未授权")
                }
            }) 
        }   
    }
    /*
     *调用时间:
     *作用:遍历通讯录
     */
    private func getContatList() {
        //判断是否有权读取通讯录
        let status = CNContactStore.authorizationStatus(for: .contacts)
        guard status == .authorized else {
            return
        }
        //1.创建通讯录对象
        let store = CNContactStore()
        //2.定义要获取的属性键值
        let key = [CNContactFamilyNameKey, CNContactGivenNameKey, CNContactPhoneNumbersKey]
        //3.获取请求对象
        let request = CNContactFetchRequest(keysToFetch: key as [CNKeyDescriptor])
        //4.遍历所有联系人
        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获取电话号码
                let phoneNumbers = contact.phoneNumbers
                for phoneNumber in phoneNumbers {
                    print(phoneNumber.label?.characters ?? "")
                    print(phoneNumber.value.stringValue)
                }
            })
        } catch {
            print("读取通讯录出错")
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读