通讯录的访问步骤一般如下:
调用ABAddressBookCreateWithOptions()方法创建通讯录对象ABAddressBookRef。
调用ABAddressBookRequestAccessWithCompletion()方法获得用户授权访问通讯录。
调用ABAddressBookCopyArrayOfAllPeople()、ABAddressBookCopyPeopleWithName()方法查询联系人信息。
读取联系人后如果要显示联系人信息则可以调用ABRecord相关方法读取相应的数据;如果要进行修改联系人信息,则可以使用对应的方法修改ABRecord信息,然后调用ABAddressBookSave()方法提交修改;如果要删除联系人,则可以调用ABAddressBookRemoveRecord()方法删除,然后调用ABAddressBookSave()提交修改操作。
也就是说如果要修改或者删除都需要首先查询对应的联系人,然后修改或删除后提交更改。如果用户要增加一个联系人则不用进行查询,直接调用ABPersonCreate()方法创建一个ABRecord然后设置具体的属性,调用ABAddressBookAddRecord方法添加即可。
class ViewController: UIViewController {
//1.创建通讯录对象ABAddressBookRef。
let addressBook: ABAddressBook = ABAddressBookCreateWithOptions(nil, nil).takeRetainedValue()
override func viewDidLoad() {
super.viewDidLoad()
//2.获得用户授权访问通讯录
ABAddressBookRequestAccessWithCompletion(addressBook){isAccess, error in
if isAccess
{
//操作
self.getAddressBookInfos()
}
}
}
func getAddressBookInfos()
{
if ABAddressBookGetAuthorizationStatus() == .Authorized
{
//3.查询联系信息
var arr = ABAddressBookCopyArrayOfAllPeople(self.addressBook).takeRetainedValue()
for record in arr as NSArray
{
//do something...
}
}
}
}
func getSysContacts() -> [[String:AnyObject]] {
var error:Unmanaged<CFError>?
var addressBook: ABAddressBookRef? = ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue()
let sysAddressBookStatus = ABAddressBookGetAuthorizationStatus()
if sysAddressBookStatus == .Denied || sysAddressBookStatus == .NotDetermined {
// Need to ask for authorization
var authorizedSingal:dispatch_semaphore_t = dispatch_semaphore_create(0)
var askAuthorization:ABAddressBookRequestAccessCompletionHandler = { success, error in
if success {
ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray
dispatch_semaphore_signal(authorizedSingal)
}
}
ABAddressBookRequestAccessWithCompletion(addressBook, askAuthorization)
dispatch_semaphore_wait(authorizedSingal, DISPATCH_TIME_FOREVER)
}
func analyzeSysContacts(sysContacts:NSArray) -> [[String:AnyObject]] {
var allContacts:Array = [[String:AnyObject]]()
func analyzeContactProperty(contact:ABRecordRef, property:ABPropertyID) -> [AnyObject]? {
var propertyValues:ABMultiValueRef? = ABRecordCopyValue(contact, property)?.takeRetainedValue()
if propertyValues != nil {
var values:Array<AnyObject> = Array()
for i in 0 ..< ABMultiValueGetCount(propertyValues) {
var value = ABMultiValueCopyValueAtIndex(propertyValues, i)
switch property {
// 地址
case kABPersonAddressProperty :
var valueDictionary:Dictionary = [String:String]()
var addrNSDict:NSMutableDictionary = value.takeRetainedValue() as NSMutableDictionary
valueDictionary["_Country"] = addrNSDict.valueForKey(kABPersonAddressCountryKey) as? String ?? ""
valueDictionary["_State"] = addrNSDict.valueForKey(kABPersonAddressStateKey) as? String ?? ""
valueDictionary["_City"] = addrNSDict.valueForKey(kABPersonAddressCityKey) as? String ?? ""
valueDictionary["_Street"] = addrNSDict.valueForKey(kABPersonAddressStreetKey) as? String ?? ""
valueDictionary["_Contrycode"] = addrNSDict.valueForKey(kABPersonAddressCountryCodeKey) as? String ?? ""
// 地址整理
var fullAddress:String = (valueDictionary["_Country"]! == "" ? valueDictionary["_Contrycode"]! : valueDictionary["_Country"]!) + ", " + valueDictionary["_State"]! + ", " + valueDictionary["_City"]! + ", " + valueDictionary["_Street"]!
values.append(fullAddress)
// SNS
case kABPersonSocialProfileProperty :
var valueDictionary:Dictionary = [String:String]()
var snsNSDict:NSMutableDictionary = value.takeRetainedValue() as NSMutableDictionary
valueDictionary["_Username"] = snsNSDict.valueForKey(kABPersonSocialProfileUsernameKey) as? String ?? ""
valueDictionary["_URL"] = snsNSDict.valueForKey(kABPersonSocialProfileURLKey) as? String ?? ""
valueDictionary["_Serves"] = snsNSDict.valueForKey(kABPersonSocialProfileServiceKey) as? String ?? ""
values.append(valueDictionary)
// IM
case kABPersonInstantMessageProperty :
var valueDictionary:Dictionary = [String:String]()
var imNSDict:NSMutableDictionary = value.takeRetainedValue() as NSMutableDictionary
valueDictionary["_Serves"] = imNSDict.valueForKey(kABPersonInstantMessageServiceKey) as? String ?? ""
valueDictionary["_Username"] = imNSDict.valueForKey(kABPersonInstantMessageUsernameKey) as? String ?? ""
values.append(valueDictionary)
// Date
case kABPersonDateProperty :
var date:String? = (value.takeRetainedValue() as? NSDate)?.description
if date != nil {
values.append(date!)
}
default :
var val:String = value.takeRetainedValue() as? String ?? ""
values.append(val)
}
}
return values
}else{
return nil
}
}
for contact in sysContacts {
var currentContact:Dictionary = [String:AnyObject]()
/*
部分单值属性
*/
// 姓、姓氏拼音
var FirstName:String = ABRecordCopyValue(contact, kABPersonFirstNameProperty)?.takeRetainedValue() as String? ?? ""
currentContact["FirstName"] = FirstName
currentContact["FirstNamePhonetic"] = ABRecordCopyValue(contact, kABPersonFirstNamePhoneticProperty)?.takeRetainedValue() as String? ?? ""
// 名、名字拼音
var LastName:String = ABRecordCopyValue(contact, kABPersonLastNameProperty)?.takeRetainedValue() as String? ?? ""
currentContact["LastName"] = LastName
currentContact["LirstNamePhonetic"] = ABRecordCopyValue(contact, kABPersonLastNamePhoneticProperty)?.takeRetainedValue() as String? ?? ""
// 昵称
currentContact["Nikename"] = ABRecordCopyValue(contact, kABPersonNicknameProperty)?.takeRetainedValue() as String? ?? ""
// 姓名整理
currentContact["fullName"] = LastName + FirstName
// 公司(组织)
currentContact["Organization"] = ABRecordCopyValue(contact, kABPersonOrganizationProperty)?.takeRetainedValue() as String? ?? ""
// 职位
currentContact["JobTitle"] = ABRecordCopyValue(contact, kABPersonJobTitleProperty)?.takeRetainedValue() as String? ?? ""
// 部门
currentContact["Department"] = ABRecordCopyValue(contact, kABPersonDepartmentProperty)?.takeRetainedValue() as String? ?? ""
// 备注
currentContact["Note"] = ABRecordCopyValue(contact, kABPersonNoteProperty)?.takeRetainedValue() as String? ?? ""
// 生日(类型转换有问题,不可用)
//currentContact["Brithday"] = ((ABRecordCopyValue(contact, kABPersonBirthdayProperty)?.takeRetainedValue()) as NSDate).description
/*
部分多值属性
*/
// 电话
var Phone:Array<AnyObject>? = analyzeContactProperty(contact, kABPersonPhoneProperty)
if Phone != nil {
currentContact["Phone"] = Phone
}
// 地址
var Address:Array<AnyObject>? = analyzeContactProperty(contact, kABPersonAddressProperty)
if Address != nil {
currentContact["Address"] = Address
}
// E-mail
var Email:Array<AnyObject>? = analyzeContactProperty(contact, kABPersonEmailProperty)
if Email != nil {
currentContact["Email"] = Email
}
// 纪念日
var Date:Array<AnyObject>? = analyzeContactProperty(contact, kABPersonDateProperty)
if Date != nil {
currentContact["Date"] = Date
}
// URL
var URL:Array<AnyObject>? = analyzeContactProperty(contact, kABPersonURLProperty)
if URL != nil{
currentContact["URL"] = URL
}
// SNS
var SNS:Array<AnyObject>? = analyzeContactProperty(contact, kABPersonSocialProfileProperty)
if SNS != nil {
currentContact["SNS"] = SNS
}
allContacts.append(currentContact)
}
return allContacts
}
return analyzeSysContacts( ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray )
}