//
//? 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