ContactsViewController.swift 2.16 KB
Newer Older
Javier Heisekce committed
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70
//
//  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!
    
    var contacts = [CNContact]()
    let contactStore = CNContactStore()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        importContacts()
        contactsTable.tableFooterView = UIView(frame: .zero)
    }
    
    func importContacts() {
        
        let keys = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]
        //obtengo
        let request = CNContactFetchRequest(keysToFetch: keys)
        request.sortOrder = CNContactSortOrder.givenName
        do {
            try self.contactStore.enumerateContacts(with: request) {
                (contact, stop) in
                // Array containing all unified contacts from everywhere
                self.contacts.append(contact)
            }
        }
        catch {
            print("unable to fetch contacts")
        }

        print(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 {
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return contacts.count
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell = tableView.dequeueReusableCell(withIdentifier: "contactName")!
        cell.textLabel?.text = "\(contacts[indexPath.row].givenName) \(contacts[indexPath.row].familyName)"
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let selectedContact = contacts[indexPath.row]
        performSegue(withIdentifier: "gotocontact", sender: selectedContact)
    }
    

}