ContactsViewController.swift 6 KB
Newer Older
Javier Heisekce committed
1 2 3 4 5 6 7 8 9 10 11 12 13
//
//  ContactsViewController.swift
//  ContactsApp
//
//  Created by User on 3/13/20.
//  Copyright © 2020 jheisecke. All rights reserved.
//

import UIKit
import ContactsUI

class ContactsViewController: UIViewController {
    
14
    @IBOutlet weak var searchBar: UISearchBar!
Javier Heisekce committed
15
    @IBOutlet weak var contactsTable: UITableView!
16 17
    var contactStructArray = [ContactStruct]()
    var contactStruct : ContactStruct?
Javier Heisekce committed
18 19 20 21
    let contactStore = CNContactStore()
    
    override func viewDidLoad() {
        super.viewDidLoad()
22
        contactsTable.register(UINib(nibName: "ContactSection", bundle: nil), forHeaderFooterViewReuseIdentifier: "headerId")
Javier Heisekce committed
23 24
        importContacts()
        contactsTable.tableFooterView = UIView(frame: .zero)
25
        searchBar.placeholder = NSLocalizedString("Nombre...", comment: "")
Javier Heisekce committed
26 27 28 29
    }
    
    func importContacts() {
        
30
        let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactEmailAddressesKey, CNContactPhoneNumbersKey, CNContactImageDataKey] as [Any]
31
        let request = CNContactFetchRequest( keysToFetch: keys as! [CNKeyDescriptor])
Javier Heisekce committed
32 33
        request.sortOrder = CNContactSortOrder.givenName
        do {
34 35 36
            var auxLetter = ""
            var contacts = [CNContact]()
            var isNotTheFirst = false
Javier Heisekce committed
37 38
            try self.contactStore.enumerateContacts(with: request) {
                (contact, stop) in
39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54
                if contact.givenName.prefix(1) == auxLetter {
                    contacts.append(contact)
                } else {
                    if isNotTheFirst {
                        let contactsExpandables = ContactStruct(isExpanded: true, contacts: contacts, letter: auxLetter)
                        self.contactStructArray.append(contactsExpandables) //guardamos el contacto expandible anterior
                        auxLetter = String(contact.givenName.prefix(1)) //guardamos la nueva letra
                        contacts = [CNContact]() //inicializamos nuevamente el array de contactos
                        contacts.append(contact) //guardamos el nuevo contacto
                    } else {
                        contacts.append(contact)
                        auxLetter = String(contact.givenName.prefix(1)) //auxLetter tiene la primera letra del nombre
                        isNotTheFirst = true //la siguiente vez que las letras no sean iguales guardara en el array
                    }

                }
Javier Heisekce committed
55
            }
56
            self.contactStructArray.append(ContactStruct(isExpanded: true, contacts: contacts, letter: auxLetter)) //agregamos el ultimo nombre
Javier Heisekce committed
57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
        }
        catch {
            print("unable to fetch contacts")
        }
    }
    
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        if let singleContactVC = segue.destination as? SingleContactViewController {
            if let selectedCnt = sender as? CNContact {
                singleContactVC.selectedContact = selectedCnt
            }
        }
    }
}
extension ContactsViewController: UITableViewDelegate, UITableViewDataSource {
72 73 74 75 76
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return contactStructArray.count
    }
    
Javier Heisekce committed
77
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
78
        if !contactStructArray[section].isExpanded {
Javier Heisekce committed
79 80 81
            return 0
        }
        
82
        return contactStructArray[section].contacts.count
Javier Heisekce committed
83 84
    }
    
Javier Heisekce committed
85
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        
Javier Heisekce committed
86
        let cell = tableView.dequeueReusableCell(withIdentifier: "contactName")!
87
        let contactCell = contactStructArray[indexPath.section].contacts[indexPath.row]
88 89 90 91 92 93 94 95 96 97 98
        
        let givenName = "\(contactCell.givenName) "
        let familyName: NSMutableAttributedString = NSMutableAttributedString(string: contactCell.familyName)
        
        let attributes: [NSAttributedString.Key: Any] = [
            .font: UIFont.boldSystemFont(ofSize: 15)
        ]
        let fullName = NSMutableAttributedString(string: givenName, attributes: attributes)
        fullName.append(familyName)
        
        cell.textLabel?.attributedText = fullName
Javier Heisekce committed
99
        
Javier Heisekce committed
100 101 102 103
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
104
        let selectedContact = contactStructArray[indexPath.section].contacts[indexPath.row]
Javier Heisekce committed
105 106 107
        performSegue(withIdentifier: "gotocontact", sender: selectedContact)
    }
    
108 109 110 111 112
    func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
113 114 115 116 117 118 119 120 121
        let header = contactsTable.dequeueReusableHeaderFooterView(withIdentifier: "headerId") as! ContactSectionView
        header.contentView.backgroundColor = .systemGray4
        header.labelExpandable.setTitle("Λ", for: .normal)
        header.labelExpandable.setTitleColor(.black, for: .normal)
        header.labelExpandable.titleLabel?.font = UIFont.boldSystemFont(ofSize: 15)
        header.labelExpandable.addTarget(self, action: #selector(interactSection), for: .touchUpInside)
        header.labelExpandable.tag = section
        header.labelLetter.text = contactStructArray[section].letter
        return header//ʌΛ
122 123
    }
    
124
    @objc func interactSection(button : UIButton) {
Javier Heisekce committed
125 126
        //contactsBackup = contacts
        let section = button.tag
127 128
        
        var indexPaths = [IndexPath]()
129
        for row in contactStructArray[section].contacts.indices {
130 131 132
            let indexPath = IndexPath(row: row, section: section)
            indexPaths.append(indexPath)
        }
Javier Heisekce committed
133

134 135
        let isExpanded = contactStructArray[section].isExpanded
        contactStructArray[section].isExpanded = !isExpanded
Javier Heisekce committed
136 137 138 139 140 141 142 143 144
        
        button.setTitle(isExpanded ? "V" : "Λ", for: .normal)
        
        if isExpanded {
            contactsTable.deleteRows(at: indexPaths, with: .top)
        } else {
            contactsTable.insertRows(at: indexPaths, with: .bottom)
        }
        
145
    }
Javier Heisekce committed
146
}