When I try to filter the Contacts properties with displayedPropertyKeys, there is something wrong with the key CNContactBirthdayKey. Even though my contact has a birthday date set, I cant see it in any ContactsUI's ViewController. In the other hand, the properties related to the phone number, or email address seem to work well. I tested it on IOS 12.1 .
Can you help me ?
Here is the code in Swift 4 :
import UIKit
import ContactsUI
class MyViewController: UIViewController, CNContactPickerDelegate {
override func viewDidLoad() {
super.viewDidLoad()
let contacts = fetchContactsWithBirthday()
let vc = CNContactPickerViewController()
vc.delegate = self
vc.displayedPropertyKeys = [CNContactNonGregorianBirthdayKey, CNContactBirthdayKey, CNContactDatesKey]
vc.predicateForEnablingContact = NSPredicate(format: "birthday.@count > 0")
self.present(vc, animated: true, completion: nil)
let vc2 = CNContactViewController(for: contacts.first!)
vc2.displayedPropertyKeys = [CNContactNonGregorianBirthdayKey, CNContactBirthdayKey, CNContactDatesKey]
self.navigationController?.pushViewController(vc2, animated: true)
}
func fetchContactsWithBirthday() -> [CNContact] {
var contacts: [CNContact] = []
let contactStore = CNContactStore()
let keys = CNContactViewController.descriptorForRequiredKeys()
let fetchReq = CNContactFetchRequest.init(keysToFetch: [CNContactGivenNameKey,CNContactFamilyNameKey, CNContactBirthdayKey, CNContactNicknameKey, CNContactImageDataAvailableKey, CNContactImageDataKey, CNContactThumbnailImageDataKey] as [CNKeyDescriptor])
fetchReq.keysToFetch.append(keys)
do {
try contactStore.enumerateContacts(with: fetchReq) {
(contact, end) in
if contact.birthday != nil {
contacts.append(contact)
}
}
}
catch {
print(error)
}
return contacts
}
}
AppDelegate : func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
window = UIWindow(frame: UIScreen.main.bounds)
window?.makeKeyAndVisible()
let vc = MyViewController()
window?.rootViewController = UINavigationController(rootViewController: vc)
return true
}