Search code examples
iosiphoneswiftaddressbook

How to count number of contacts in swift?


how to count number of contacts in swift ,i am very new to this ios platform i just wanted know how to access contact and count it. any valid inputs will be appreciated.

       //
//  ViewController.swift
//  test1
//
//  Created by Lakshmi Kanth N on 6/23/17.
//  Copyright © 2017 Lakshmi Kanth N. All rights reserved.
//

import UIKit
import Contacts
import ContactsUI
import AddressBook

class ViewController: UIViewController, CNContactPickerDelegate{

    @IBOutlet var label: UILabel!

    @IBOutlet var click: UIButton!





    override func viewDidLoad() {
        super.viewDidLoad()
        let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName)]

        // The container means
        // that the source the contacts from, such as Exchange and iCloud
        var allContainers: [CNContainer] = []
        do {
            allContainers = try contactStore.containersMatchingPredicate(nil)
        } catch {
            print("Error fetching containers")
        }
        print (allContainers.count)


        // Do any additional setup after loading the view, typically from a nib.
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    @IBAction func obclick(_ sender: UIButton) {

        let entieyType = CNEntityType.contacts
        let authStatus = CNContactStore.authorizationStatus(for: entieyType)

        if authStatus == CNAuthorizationStatus.notDetermined{

            let contactStore = CNContactStore.init()
            contactStore.requestAccess(for: entieyType, completionHandler: { (success, nil) in

                if success {

                    self.openContacts()
                }

                else {
                    print("NOT")
                }

            })

        }
        else if authStatus == CNAuthorizationStatus.authorized{
            self.openContacts()

        }
    }


    func openContacts (){

        let contactPicker = CNContactPickerViewController.init()
        contactPicker.delegate = self
        self.present(contactPicker, animated: true, completion: nil)



    }


    func contactPickerDidCancel(_ picker: CNContactPickerViewController) {
        picker.dismiss(animated: true) {

        }
    }

    func contactPicker(_ picker: CNContactPickerViewController, didSelect contact: CNContact) {


    }




}

above is my code which is used to access the contacts but i need to have a count of them


Solution

  • // You may add more "keys" to fetch referred to official documentation
    let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName)]
    
    // The container means 
    // that the source the contacts from, such as Exchange and iCloud
    var allContainers: [CNContainer] = []
    do {
        allContainers = try contactStore.containersMatchingPredicate(nil)
    } catch {
        print("Error fetching containers")
    }
    print (allContainers.count)
    

    if u want to check for valid input for searching

    var contacts: [CNContact] = []
    for container in allContainers {
        let fetchPredicate = CNContact.predicateForContactsInContainerWithIdentifier(container.identifier)
    
        do {
            let containerResults = try contactStore.unifiedContactsMatchingPredicate(fetchPredicate, keysToFetch: keysToFetch)
            // Put them into "contacts"
            contacts.appendContentsOf(containerResults)
        } catch {
            print("Error fetching results for container")
        }
    }
    print (containerResults.count)