Swift - 读取通讯录信息

1,通讯录访问介绍
通讯录是一个数据库,又叫地址簿、电话簿,里面储存了联系人的相关信息。要实现访问通讯录有如下两种方式:
(1)AddressBook.framework框架 : 没有界面,通过代码来获取所有联系人信息
(2)AddressBookUI.framework框架 : 通过系统提供的通讯录交互界面来访问

2,联系人记录的属性
在一条联系人记录中,有很多属性,而这些属性又分为单值属性和多值属性。
(1)单值属性是只有一个值的属性:
kABPersonLastNameProperty :姓
kABPersonFirstNameProperty :名
kABPersonMiddleNameProperty :中间名
kABPersonPrefixProperty :前缀
kABPersonSuffixProperty :后缀
kABPersonLastNamePhoneticProperty :姓氏汉语拼音或音标
kABPersonFirstNamePhoneticProperty :名字汉语拼音或音标
kABPersonNicknameProperty :昵称
kABPersonOrganizationProperty :公司(组织)
kABPersonJobTitleProperty :职位
kABPersonDepartmentProperty :部门
kABPersonNoteProperty :备注

(2)多值属性是包含多个值的集合类型:
kABPersonPhoneProperty :电话
kABPersonEmailProperty :Email
kABPersonAddressProperty :地址
kABPersonURLProperty : URL属性
kABPersonDateProperty :纪念日
kABPersonInstantMessageProperty :获取即时通讯(IM)
kABPersonSocialProfileProperty :社交账号
kABPersonRelatedNamesProperty :亲属关系人

3,多值属性标签的本地名称
在多值属性中包含了label(标签)、value(值)和ID等部分,其中标签和值都是可以重复的,而ID是不能重复的。
对于标签,我们可以使用ABAddressBookCopyLocalizedLabel()方法转为本地标签名(即能看得懂的标签名,比如work、home)。要不然打印出来的是 !<Home>! !<Work>! 这样的数据。

4,下面样例使用代码遍历所有的联系人,并打印输出相关属性

import UIKit
import AddressBook
import AddressBookUI

class ViewController: UIViewController {

    //address Book对象,用来获取电话簿句柄
    var addressBook:ABAddressBookRef?

    override func viewDidLoad() {
        super.viewDidLoad()

        //定义一个错误标记对象,判断是否成功

        var error:Unmanaged<CFErrorRef>?
        addressBook = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()

        //发出授权信息
        let sysAddressBookStatus = ABAddressBookGetAuthorizationStatus()
        if (sysAddressBookStatus == ABAuthorizationStatus.NotDetermined) {
            print("requesting access...")
// var errorRef:Unmanaged<CFError>? = nil
            //addressBook = extractABAddressBookRef(ABAddressBookCreateWithOptions(nil, &errorRef))
            ABAddressBookRequestAccessWithCompletion(addressBook, { success, error in
                if success {
                    //获取并遍历所有联系人记录
                    self.readRecords();
                }
                else {
                    print("error")
                }
            })
        }
        else if (sysAddressBookStatus == ABAuthorizationStatus.Denied || sysAddressBookStatus == ABAuthorizationStatus.Restricted) {
            print("access denied")
        }
        else if (sysAddressBookStatus == ABAuthorizationStatus.Authorized) {
            print("access granted")
            //获取并遍历所有联系人记录
            self.readRecords();
        }
    }

    //获取并遍历所有联系人记录
    func readRecords(){
        let sysContacts:NSArray = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray
        for contact in sysContacts {
            //获取姓
            let lastName = ABRecordCopyValue(contact, kABPersonLastNameProperty)?.takeRetainedValue() as! String? ?? ""
            print("姓:\(lastName)")

            //获取名
            let firstName = ABRecordCopyValue(contact, kABPersonFirstNameProperty)?.takeRetainedValue() as! String? ?? ""
            print("名:\(firstName)")

            //昵称
            let nikeName = ABRecordCopyValue(contact, kABPersonNicknameProperty)?.takeRetainedValue() as! String? ?? ""
            print("昵称:\(nikeName)")

            //公司(组织)
            let organization = ABRecordCopyValue(contact, kABPersonOrganizationProperty)?.takeRetainedValue() as! String? ?? ""
            print("公司(组织):\(organization)")

            //职位
            let jobTitle = ABRecordCopyValue(contact, kABPersonJobTitleProperty)?.takeRetainedValue() as! String? ?? ""
            print("职位:\(jobTitle)")

            //部门
            let department = ABRecordCopyValue(contact, kABPersonDepartmentProperty)?.takeRetainedValue() as! String? ?? ""
            print("部门:\(department)")

            //备注
            let note = ABRecordCopyValue(contact, kABPersonNoteProperty)?.takeRetainedValue() as! String? ?? ""
            print("备注:\(note)")

            //获取电话
            let phoneValues:ABMutableMultiValueRef? = ABRecordCopyValue(contact, kABPersonPhoneProperty).takeRetainedValue()
            if phoneValues != nil {
                print("电话:\(ABMultiValueGetCount(phoneValues))")
                if ABMultiValueGetCount(phoneValues)==1 {
                    for i in 0 ..< ABMultiValueGetCount(phoneValues){
                        if ABMultiValueCopyLabelAtIndex(phoneValues, i) != nil {

                            // 获得标签名
                            let phoneLabel = ABMultiValueCopyLabelAtIndex(phoneValues, i).takeRetainedValue()
                                as CFStringRef;
                            // 转为本地标签名(能看得懂的标签名,比如work、home)
                            let localizedPhoneLabel = ABAddressBookCopyLocalizedLabel(phoneLabel).takeRetainedValue() as String

                            let value = ABMultiValueCopyValueAtIndex(phoneValues, i)
                            let phone = value.takeRetainedValue() as! String
                            print(" \(localizedPhoneLabel):\(phone)")
                        }
                    }
                }
            }

            //获取Email
            let emailValues:ABMutableMultiValueRef? = ABRecordCopyValue(contact, kABPersonEmailProperty).takeRetainedValue()
            if emailValues != nil {
                print("Email:")
                for i in 0 ..< ABMultiValueGetCount(emailValues){
                    if ABMultiValueCopyLabelAtIndex(emailValues, i) != nil {
                        // 获得标签名
                        let label = ABMultiValueCopyLabelAtIndex(emailValues, i).takeRetainedValue()
                            as CFStringRef;
                        let localizedLabel = ABAddressBookCopyLocalizedLabel(label).takeRetainedValue() as String

                        let value = ABMultiValueCopyValueAtIndex(emailValues, i)
                        let email = value.takeRetainedValue() as! String
                        print(" \(localizedLabel):\(email)")
                    }
                }
            }

            //获取地址
            let addressValues:ABMutableMultiValueRef? = ABRecordCopyValue(contact, kABPersonAddressProperty).takeRetainedValue()
            if addressValues != nil {
                print("地址:")
                for i in 0 ..< ABMultiValueGetCount(addressValues){

                    // 获得标签名
                    let label = ABMultiValueCopyLabelAtIndex(addressValues, i).takeRetainedValue()
                        as CFStringRef;
                    let localizedLabel = ABAddressBookCopyLocalizedLabel(label).takeRetainedValue() as String

                    let value = ABMultiValueCopyValueAtIndex(addressValues, i)
                    let addrNSDict:NSMutableDictionary = value.takeRetainedValue()
                        as! NSMutableDictionary
                    let country:String = addrNSDict.valueForKey(kABPersonAddressCountryKey as String)
                        as? String ?? ""
                    let state:String = addrNSDict.valueForKey(kABPersonAddressStateKey as String)
                        as? String ?? ""
                    let city:String = addrNSDict.valueForKey(kABPersonAddressCityKey as String)
                        as? String ?? ""
                    let street:String = addrNSDict.valueForKey(kABPersonAddressStreetKey as String)
                        as? String ?? ""
                    let contryCode:String = addrNSDict.valueForKey(kABPersonAddressCountryCodeKey as String) as? String ?? ""
                    print(" \(localizedLabel): Contry:\(country) State:\(state) ")
                    print("City:\(city) Street:\(street) ContryCode:\(contryCode) ")
                }
            }

            //获取纪念日
            let dateValues:ABMutableMultiValueRef? = ABRecordCopyValue(contact, kABPersonDateProperty).takeRetainedValue()
            if dateValues != nil {
                print("纪念日:")
                for i in 0 ..< ABMultiValueGetCount(dateValues){

                    // 获得标签名
                    let label = ABMultiValueCopyLabelAtIndex(emailValues, i).takeRetainedValue()
                        as CFStringRef;
                    let localizedLabel = ABAddressBookCopyLocalizedLabel(label).takeRetainedValue() as String
                    let value = ABMultiValueCopyValueAtIndex(dateValues, i)
                    let date = (value.takeRetainedValue() as? NSDate)?.description ?? ""
                    print(" \(localizedLabel):\(date)")
                }
            }

            //获取即时通讯(IM)
            let imValues:ABMutableMultiValueRef? = ABRecordCopyValue(contact, kABPersonInstantMessageProperty).takeRetainedValue()
            if imValues != nil {
                print("即时通讯(IM):")
                for i in 0 ..< ABMultiValueGetCount(imValues){
                    if ABMultiValueCopyLabelAtIndex(imValues, i) != nil {
                        // 获得标签名
                        let label = ABMultiValueCopyLabelAtIndex(imValues, i).takeRetainedValue()
                            as CFStringRef;
                        let localizedLabel = ABAddressBookCopyLocalizedLabel(label).takeRetainedValue() as String
                        let value = ABMultiValueCopyValueAtIndex(imValues, i)
                        let imNSDict:NSMutableDictionary = value.takeRetainedValue()
                            as! NSMutableDictionary
                        let serves:String = imNSDict.valueForKey(kABPersonInstantMessageServiceKey as String) as? String ?? ""
                        let userName:String = imNSDict.valueForKey(kABPersonInstantMessageUsernameKey as String) as? String ?? ""
                        print(" \(localizedLabel): Serves:\(serves) UserName:\(userName)")
                    }
                }
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
    }
}

你可能感兴趣的:(数据库,swift,通讯录,联系人信息)