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

import UIKit
import ContactsUI

class ContactsViewController: UIViewController {
    
    @IBOutlet weak var contactsTable: UITableView!
15 16
    var contactStructArray = [ContactStruct]()
    var contactStruct : ContactStruct?
Javier Heisekce committed
17 18 19 20
    let contactStore = CNContactStore()
    
    override func viewDidLoad() {
        super.viewDidLoad()
21
        contactsTable.register(UINib(nibName: "ContactSection", bundle: nil), forHeaderFooterViewReuseIdentifier: "headerId")
Javier Heisekce committed
22 23 24 25 26 27
        importContacts()
        contactsTable.tableFooterView = UIView(frame: .zero)
    }
    
    func importContacts() {
        
28 29
        let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName), CNContactEmailAddressesKey, CNContactPhoneNumbersKey, CNContactImageDataKey, CNContactImageDataAvailableKey] as [Any]
        let request = CNContactFetchRequest( keysToFetch: keys as! [CNKeyDescriptor])
Javier Heisekce committed
30 31
        request.sortOrder = CNContactSortOrder.givenName
        do {
32 33 34
            var auxLetter = ""
            var contacts = [CNContact]()
            var isNotTheFirst = false
Javier Heisekce committed
35 36
            try self.contactStore.enumerateContacts(with: request) {
                (contact, stop) in
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52
                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
53
            }
54 55 56 57
            self.contactStructArray.append(ContactStruct(isExpanded: true, contacts: contacts, letter: auxLetter)) //agregamos el ultimo nombre
            print("CONTACTOS ORDENADOS")
            print(self.contactStructArray)
            print("======================")
Javier Heisekce committed
58 59 60 61 62 63 64 65 66 67 68 69 70 71 72
        }
        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 {
73 74 75 76 77
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return contactStructArray.count
    }
    
Javier Heisekce committed
78
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
79
        if !contactStructArray[section].isExpanded {
Javier Heisekce committed
80 81 82
            return 0
        }
        
83
        return contactStructArray[section].contacts.count
Javier Heisekce committed
84 85
    }
    
Javier Heisekce committed
86
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {        
Javier Heisekce committed
87
        let cell = tableView.dequeueReusableCell(withIdentifier: "contactName")!
88
        let contactCell = contactStructArray[indexPath.section].contacts[indexPath.row]
89 90 91 92 93 94 95 96 97 98 99
        
        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
100
        
Javier Heisekce committed
101 102 103 104
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
105
        let selectedContact = contactStructArray[indexPath.section].contacts[indexPath.row]
Javier Heisekce committed
106 107 108
        performSegue(withIdentifier: "gotocontact", sender: selectedContact)
    }
    
109 110 111 112 113
    func tableView(_ tableView: UITableView, estimatedHeightForHeaderInSection section: Int) -> CGFloat {
        return 40
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
114 115 116 117 118 119 120 121 122
        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//ʌΛ
123 124
    }
    
125
    @objc func interactSection(button : UIButton) {
Javier Heisekce committed
126 127
        //contactsBackup = contacts
        let section = button.tag
128 129
        
        var indexPaths = [IndexPath]()
130
        for row in contactStructArray[section].contacts.indices {
131 132 133
            let indexPath = IndexPath(row: row, section: section)
            indexPaths.append(indexPath)
        }
Javier Heisekce committed
134

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