如何计算swift中的联系人数量 ,我对这个ios平台很新,我只是想知道如何访问联系并计算它。任何有效的输入将不胜感激。
//
// 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) {
}
}
上面是我的代码,用于访问联系人,但我需要计算它们
答案 0 :(得分:1)
if item.isKeyAvailable(CNContactPhoneNumbersKey){
let phoneNOs=item.phoneNumbers
print("Phone No count \(phoneNOs.count)")
}
答案 1 :(得分:-1)
// 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)
如果你想检查有效的搜索输入
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)