swift 实现通讯录

第一步:获取授权,在viewDidLoad 里面写一下的代码

//新通讯录获得授权方法

//用新的方法获取通讯录信息,首先获取 store

var store = CNContactStore()

let status  = CNContactStore.authorizationStatusForEntityType(.Contacts)

if status == CNAuthorizationStatus.NotDetermined{

print("requesting access")

self.store.requestAccessForEntityType(CNEntityType.Contacts,completionHandler: { (result, error) -> Void in

if result == true{

print("已授权")

//获取并遍历所有联系人记录

self.readRecord()

self.fetchContactList()

dispatch_async(dispatch_get_main_queue(), { () -> Void in

//gContactViewController?.contactTableView.reloadData()

self.listTableView.reloadData()

})

}else{

print("error")

}

})

}

else if (status == CNAuthorizationStatus.Denied){

print("access denied")

}

else if (status == CNAuthorizationStatus.Authorized){

self.readRecord()

self.fetchContactList()

}

// 第二步,接下来,是readRecord() 函数的实现,主要用于获取数据,并加以封装

func readRecord() {

//获取Contacts方法

let store = CNContactStore()

let keysToFetch =  [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),CNContactImageDataKey,CNContactPhoneNumbersKey]

let fetchRequest = CNContactFetchRequest(keysToFetch: keysToFetch)

var contacts = [CNContact]()

do {

try store.enumerateContactsWithFetchRequest(fetchRequest, usingBlock: { (let contact, let stop) -> Void in

contacts.append(contact)

})

//try contacts = store.unifiedContactsMatchingPredicate(predicate, keysToFetch: keys)

}

catch let error as NSError {

print(error.localizedDescription)

}

print("contacts accounts is\(contacts.count)")

for contact in contacts {

var i = 0

//获取本地通讯录头像数据

var imageData: NSData = NSData()

if (contact.isKeyAvailable(CNContactImageDataKey) == true){

if contact.imageData != nil{

imageData = contact.imageData!

}

}

//获取姓名

let name = CNContactFormatter.stringFromContact(contact, style: .FullName) as String? ?? ""

//获取姓名拼音

var nameSpell:String = name.pinYin()

if nameSpell == ""{

nameSpell = "#"

}

//获取电话号码

let tempphone = contact.phoneNumbers.first?.value as? CNPhoneNumber

var phone = tempphone?.stringValue

if  phone == nil

{

phone = " "

}

//获取本地通讯录头像图片

var image: UIImage?

if imageData.length != 0 {

image = UIImage.init(data: imageData)

}else{

image = nil

}

//如果没有头像,本地通讯录没有头像,则默认给一个头像

var avatar_url: String = ""

avatar_url = "http://ww2.sinaimg.cn/large/6a011e49jw1f18hkv6i5kj20300303yb.jpg"

//把拿到的数据放到contactModelArray 里面

let model = ContactModel()

model.avatarSmallURL = avatar_url

model.nameSpell = nameSpell

model.chineseName = name

model.imageIco = image

model.phone = phone

contactModelArray.insertObject(model, atIndex: i)

print("contactModelArrays is\(contactModelArray.count)")

contactDic = ["name":name, "phone":phone!,"avatar_url":avatar_url,"name_spell":nameSpell]

contactArray.insertObject(contactDic!, atIndex: i)

i = i+1

}

}

通过这两步就可以轻松拿到数据了。因为fetchContactList() 是自己根据自己业务逻辑写的,比较复杂就不贴出来了。有需要的可以联系我。下面就放出效果图吧。

swift 实现通讯录_第1张图片

你可能感兴趣的:(swift 实现通讯录)