Contact.framework聯(lián)系人相關(guān)操作

//

//? ViewController.swift

//? ContactClean

//

//? Created by zhangzb on 2019/7/31.

//? Copyright ? 2019 zhangzb. All rights reserved.

//

/*

1断国、引入Contacts框架

2、檢查授權(quán)狀態(tài)

3匿乃、獲取聯(lián)系人

4合敦、展示初橘、增刪改查操作

5、info.plist增加字段

*/

import UIKit

// 引入Contacts框架

import Contacts

class ViewController: UIViewController {

? ? // 所有聯(lián)系人都是CNContact類型的數(shù)據(jù)充岛,所以直接使用系統(tǒng)的CNContact實體類

? ? var contacts = [CNContact]()

? ? @IBOutlet var tableView: UITableView!


? ? override func viewDidLoad() {

? ? ? ? super.viewDidLoad()

? ? ? ? // 檢查狀態(tài)

? ? ? ? if self.checkAuthStatus() {

? ? ? ? ? ? // 如果已授權(quán)保檐,那么直接拉取數(shù)據(jù)

? ? ? ? ? ? self.requestAllContacts()

? ? ? ? }

? ? }


? ? /// 檢查授權(quán)狀態(tài),true已授權(quán)崔梗,false未授權(quán)

? ? func checkAuthStatus() -> Bool {

? ? ? ? weak var weakSelf = self

? ? ? ? // 獲取授權(quán)狀態(tài)

? ? ? ? switch CNContactStore.authorizationStatus(for: .contacts) {

? ? ? ? // 不允許夜只,沒有權(quán)限

? ? ? ? case .denied:

? ? ? ? ? ? let alertController = UIAlertController(title: "未授權(quán)", message: "您關(guān)閉了App訪問通訊錄的權(quán)限,請先去開啟后重試", preferredStyle: .alert)

? ? ? ? ? ? alertController.addAction(UIAlertAction(title: "去開啟", style: .default, handler: { (_) in

? ? ? ? ? ? ? ? weakSelf?.goToSetting()

? ? ? ? ? ? }))

? ? ? ? ? ? alertController.addAction(UIAlertAction(title: "取消", style: .cancel, handler: { (_) in


? ? ? ? ? ? }))

? ? ? ? ? ? self.present(alertController, animated: true, completion: nil)

? ? ? ? // 未授權(quán)蒜魄,restricted(因為一些原因沒有授權(quán))

? ? ? ? case .notDetermined, .restricted:

? ? ? ? ? ? // 申請授權(quán)

? ? ? ? ? ? CNContactStore().requestAccess(for: .contacts) { (success, error) in

? ? ? ? ? ? ? ? if success, error == nil {

? ? ? ? ? ? ? ? ? ? let alertController = UIAlertController(title: "成功", message: "授權(quán)成功", preferredStyle: .alert)

? ? ? ? ? ? ? ? ? ? alertController.addAction(UIAlertAction(title: "確定", style: .default, handler: { (_) in

? ? ? ? ? ? ? ? ? ? ? ? // 由于會優(yōu)先返回false扔亥,所以第一次授權(quán)彈窗時不會刷新數(shù)據(jù)场躯,在授權(quán)成功之后需要重新調(diào)用刷新方法

? ? ? ? ? ? ? ? ? ? ? ? weakSelf?.requestAllContacts()

? ? ? ? ? ? ? ? ? ? }))

? ? ? ? ? ? ? ? ? ? weakSelf?.present(alertController, animated: true, completion: nil)

? ? ? ? ? ? ? ? } else {

? ? ? ? ? ? ? ? ? ? let alertController = UIAlertController(title: "錯誤", message: "授權(quán)失敗", preferredStyle: .alert)

? ? ? ? ? ? ? ? ? ? alertController.addAction(UIAlertAction(title: "確定", style: .cancel, handler: { (_) in


? ? ? ? ? ? ? ? ? ? }))

? ? ? ? ? ? ? ? ? ? weakSelf?.present(alertController, animated: true, completion: nil)

? ? ? ? ? ? ? ? }

? ? ? ? ? ? }

? ? ? ? // 已允許

? ? ? ? case .authorized:

? ? ? ? ? ? print("Authorized")

? ? ? ? ? ? return true

? ? ? ? // CNAuthorizationStatus 可能會在將來添加狀態(tài),所以Apple要求寫@unknown default狀態(tài)旅挤,試試注掉會報警告

? ? ? ? // Switch covers known cases, but 'CNAuthorizationStatus' may have additional unknown values, possibly added in future versions

? ? ? ? @unknown default:

? ? ? ? ? ? let alertController = UIAlertController(title: "錯誤", message: "授權(quán)失敗", preferredStyle: .alert)

? ? ? ? ? ? alertController.addAction(UIAlertAction(title: "確定", style: .cancel, handler: { (_) in

? ? ? ? ? ? }))

? ? ? ? ? ? weakSelf?.present(alertController, animated: true, completion: nil)

? ? ? ? }

? ? ? ? // 只有在允許的情況下才返回true

? ? ? ? return false

? ? }


? ? /// 刷新數(shù)據(jù)

? ? func requestAllContacts() {

? ? ? ? self.contacts.removeAll()

? ? ? ? weak var weakSelf = self

? ? ? ? let contactStore = CNContactStore()

? ? ? ? do {

? ? ? ? ? ? // 此處列舉需要獲取的聯(lián)系人數(shù)據(jù)的key踢关,eg. CNContactGivenNameKey

? ? ? ? ? ? try contactStore.enumerateContacts(with: CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactPhoneNumbersKey] as [CNKeyDescriptor])) { (contact, stop) in

? ? ? ? ? ? ? ? weakSelf?.contacts.append(contact)

? ? ? ? ? ? }

? ? ? ? ? ? self.tableView.reloadData()

? ? ? ? } catch {

? ? ? ? ? ? print(error)

? ? ? ? }


? ? }


? ? // 跳轉(zhuǎn)設(shè)置頁面

? ? func goToSetting() {

? ? ? ? if let settingUrl = URL(string: UIApplication.openSettingsURLString), UIApplication.shared.canOpenURL(settingUrl) {

? ? ? ? ? ? UIApplication.shared.open(settingUrl)

? ? ? ? }

? ? }


? ? // 增加一個

? ? @IBAction func addOne() {

? ? ? ? // 創(chuàng)建一個新的contact

? ? ? ? let contact = CNMutableContact()

? ? ? ? contact.givenName = "aaaaa\(arc4random_uniform(100))"

? ? ? ? contact.familyName = "bb\(arc4random_uniform(100))"

? ? ? ? var phones = [CNLabeledValue<CNPhoneNumber>]()

? ? ? ? for _ in 0...arc4random_uniform(5) {

? ? ? ? ? ? let phoneValue = CNLabeledValue(label: "手機(jī)", value: CNPhoneNumber(stringValue: "130000\(arc4random_uniform(99999))"))

? ? ? ? ? ? phones.append(phoneValue)

? ? ? ? }

? ? ? ? contact.phoneNumbers = phones


? ? ? ? // 創(chuàng)建保存saveRequest

? ? ? ? let saveRequest = CNSaveRequest()

? ? ? ? saveRequest.add(contact, toContainerWithIdentifier: nil)

? ? ? ? self.excute(saveRequest: saveRequest)

? ? }


? ? // 刪

? ? func deleteOne(contact: CNContact) {

? ? ? ? // 創(chuàng)建刪除saveRequest

? ? ? ? let saveRequest = CNSaveRequest()

? ? ? ? saveRequest.delete(contact.mutableCopy() as! CNMutableContact)

? ? ? ? self.excute(saveRequest: saveRequest)

? ? }


? ? // 改

? ? func updateOne(contact: CNContact) {

? ? ? ? // 修改對應(yīng)的聯(lián)系人信息

? ? ? ? let mutableContact = contact.mutableCopy() as! CNMutableContact

? ? ? ? mutableContact.givenName = "aaaaa\(arc4random_uniform(100))"

? ? ? ? mutableContact.familyName = "bb\(arc4random_uniform(100))"

? ? ? ? var phones = [CNLabeledValue<CNPhoneNumber>]()

? ? ? ? for _ in 0...arc4random_uniform(5) {

? ? ? ? ? ? let phoneValue = CNLabeledValue(label: "手機(jī)", value: CNPhoneNumber(stringValue: "130000\(arc4random_uniform(99999))"))

? ? ? ? ? ? phones.append(phoneValue)

? ? ? ? }

? ? ? ? mutableContact.phoneNumbers = phones


? ? ? ? // 創(chuàng)建修改saveRequest

? ? ? ? let saveRequest = CNSaveRequest()

? ? ? ? saveRequest.update(mutableContact)

? ? ? ? self.excute(saveRequest: saveRequest)

? ? }


? ? // 執(zhí)行request

? ? func excute(saveRequest: CNSaveRequest) {

? ? ? ? do {

? ? ? ? ? ? try CNContactStore().execute(saveRequest)

? ? ? ? ? ? print("保存成功")

? ? ? ? ? ? self.requestAllContacts()

? ? ? ? } catch {

? ? ? ? ? ? print(error)

? ? ? ? }

? ? }

}

// 聯(lián)系人cell

class CCContactCell: UITableViewCell {

? ? /// 姓名

? ? @IBOutlet var nameLabel: UILabel!

? ? /// 手機(jī)號碼

? ? @IBOutlet var phoneLabel: UILabel!


? ? func updateUI(contact: CNContact) {

? ? ? ? self.nameLabel.text = contact.givenName + contact.familyName

? ? ? ? var phones = [String]()

? ? ? ? for phone in contact.phoneNumbers {

? ? ? ? ? ? phones.append(phone.value.stringValue)

? ? ? ? }

? ? ? ? self.phoneLabel.text = phones.joined(separator: ",")

? ? }

}

extension ViewController: UITableViewDataSource, UITableViewDelegate {

? ? func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {

? ? ? ? return self.contacts.count

? ? }


? ? func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {

? ? ? ? var cell = tableView.dequeueReusableCell(withIdentifier: "ContactCell") as? CCContactCell

? ? ? ? if cell == nil {

? ? ? ? ? ? cell = CCContactCell(style: .default, reuseIdentifier: "ContactCell")

? ? ? ? }

? ? ? ? cell?.updateUI(contact: self.contacts[indexPath.row])

? ? ? ? return cell ?? CCContactCell()

? ? }


? ? func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

? ? ? ? // 點擊cell時更新聯(lián)系人的信息

? ? ? ? self.updateOne(contact: self.contacts[indexPath.row])

? ? }


? ? func tableView(_ tableView: UITableView, editingStyleForRowAt indexPath: IndexPath) -> UITableViewCell.EditingStyle {

? ? ? ? return .delete

? ? }


? ? func tableView(_ tableView: UITableView, commit editingStyle: UITableViewCell.EditingStyle, forRowAt indexPath: IndexPath) {

? ? ? ? // 刪除聯(lián)系人的信息

? ? ? ? self.deleteOne(contact: self.contacts[indexPath.row])

? ? }

}

最后,別忘了在項目info.plist中添加NSContactsUsageDescription

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末谦铃,一起剝皮案震驚了整個濱河市耘成,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌驹闰,老刑警劉巖,帶你破解...
    沈念sama閱讀 217,406評論 6 503
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件撒会,死亡現(xiàn)場離奇詭異嘹朗,居然都是意外死亡,警方通過查閱死者的電腦和手機(jī)诵肛,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 92,732評論 3 393
  • 文/潘曉璐 我一進(jìn)店門屹培,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人怔檩,你說我怎么就攤上這事褪秀。” “怎么了薛训?”我有些...
    開封第一講書人閱讀 163,711評論 0 353
  • 文/不壞的土叔 我叫張陵媒吗,是天一觀的道長。 經(jīng)常有香客問我乙埃,道長闸英,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,380評論 1 293
  • 正文 為了忘掉前任介袜,我火速辦了婚禮甫何,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘遇伞。我一直安慰自己辙喂,他們只是感情好,可當(dāng)我...
    茶點故事閱讀 67,432評論 6 392
  • 文/花漫 我一把揭開白布鸠珠。 她就那樣靜靜地躺著巍耗,像睡著了一般。 火紅的嫁衣襯著肌膚如雪跳芳。 梳的紋絲不亂的頭發(fā)上芍锦,一...
    開封第一講書人閱讀 51,301評論 1 301
  • 那天,我揣著相機(jī)與錄音飞盆,去河邊找鬼娄琉。 笑死次乓,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的孽水。 我是一名探鬼主播票腰,決...
    沈念sama閱讀 40,145評論 3 418
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼女气!你這毒婦竟也來了杏慰?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,008評論 0 276
  • 序言:老撾萬榮一對情侶失蹤炼鞠,失蹤者是張志新(化名)和其女友劉穎缘滥,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體谒主,經(jīng)...
    沈念sama閱讀 45,443評論 1 314
  • 正文 獨居荒郊野嶺守林人離奇死亡朝扼,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,649評論 3 334
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了霎肯。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片擎颖。...
    茶點故事閱讀 39,795評論 1 347
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖观游,靈堂內(nèi)的尸體忽然破棺而出搂捧,到底是詐尸還是另有隱情,我是刑警寧澤懂缕,帶...
    沈念sama閱讀 35,501評論 5 345
  • 正文 年R本政府宣布允跑,位于F島的核電站,受9級特大地震影響提佣,放射性物質(zhì)發(fā)生泄漏吮蛹。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 41,119評論 3 328
  • 文/蒙蒙 一拌屏、第九天 我趴在偏房一處隱蔽的房頂上張望潮针。 院中可真熱鬧,春花似錦倚喂、人聲如沸每篷。這莊子的主人今日做“春日...
    開封第一講書人閱讀 31,731評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽焦读。三九已至,卻和暖如春舱权,著一層夾襖步出監(jiān)牢的瞬間矗晃,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 32,865評論 1 269
  • 我被黑心中介騙來泰國打工宴倍, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留张症,地道東北人仓技。 一個月前我還...
    沈念sama閱讀 47,899評論 2 370
  • 正文 我出身青樓,卻偏偏與公主長得像俗他,于是被迫代替她去往敵國和親脖捻。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 44,724評論 2 354