ContactsUI ViewControllers中的CNContactBirthdayKey被忽略

时间:2018-12-14 15:56:14

标签: ios swift contacts

当我尝试使用displayPropertyKeys过滤Contacts属性时,键CNContactBirthdayKey出了点问题。即使我的联系人设置了生日,我也无法在任何ContactsUI的ViewController中看到它。在ios 12.1,IOS 11.0和10.3.3上进行了测试。

未设置displayPropertyKeys:

enter image description here

with displayPropertyKeys = [CNContactBirthdayKey]:

enter image description here

你能帮我吗?

这是Swift 4中的代码:

带有CNContactPickerViewController()的示例:

import UIKit
import ContactsUI

class MyViewController: UIViewController, CNContactPickerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let vc = CNContactPickerViewController()

        vc.delegate = self
        vc.displayedPropertyKeys = [CNContactBirthdayKey]

        self.present(vc, animated: true, completion: nil)
    }
}

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
}

CNContactViewController()的示例:

import UIKit
import ContactsUI

class MyViewController: UIViewController, CNContactPickerDelegate {

    override func viewDidLoad() {
        super.viewDidLoad()

        let contacts = fetchContactsWithBirthday()

        let vc2 = CNContactViewController(for: contacts.first!)

        vc2.displayedPropertyKeys = [CNContactBirthdayKey]

        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
    }

0 个答案:

没有答案