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: "手機", 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: "手機", 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!

? ? /// 手機號碼

? ? @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)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

友情鏈接更多精彩內(nèi)容