如何批量访问iOS联系人?

如何批量访问iOS联系人?,ios,swift,xamarin,xamarin.ios,ios-contacts,Ios,Swift,Xamarin,Xamarin.ios,Ios Contacts,我正在尝试在Xamarin.iOS中实现一个联系人阅读器,它尝试在所有CNContactStore容器中迭代iOS联系人。我不需要将所有联系人加载到内存中,而是需要一批一批地迭代联系人结果集(分页联系人)。然而,我在中看到的所有示例都是首先将几乎所有联系人加载到内存中 i、 e.具有大量类似示例,可一次读取所有触点。虽然这些例子有一个接一个迭代的逻辑,但我不清楚如何跳过N个联系人,在下一次呼叫时不从一开始就进行迭代(至少在我看来,这是次优的) 阅读 我可以使用Android SDK中提供的基于光

我正在尝试在Xamarin.iOS中实现一个联系人阅读器,它尝试在所有CNContactStore容器中迭代iOS联系人。我不需要将所有联系人加载到内存中,而是需要一批一批地迭代联系人结果集(分页联系人)。然而,我在中看到的所有示例都是首先将几乎所有联系人加载到内存中

i、 e.具有大量类似示例,可一次读取所有触点。虽然这些例子有一个接一个迭代的逻辑,但我不清楚如何跳过N个联系人,在下一次呼叫时不从一开始就进行迭代(至少在我看来,这是次优的)

阅读

我可以使用Android SDK中提供的基于光标的方法轻松完成这项工作。这对iOS来说可能吗?如果没有,我们如何处理大量联系人(例如,2000人以上的联系人等)。我不介意斯威夫特的例子。我应该可以把它们转换成Xamarin


提前感谢。

这是我采取的方法,假设我的需求不允许持久联系人,只允许在活动内存中保存。并不是说这是正确的方法,而是首先获取所有标识符,然后根据需要惰性地获取特定联系人的所有密钥,这确实提高了性能。它还可以避免在联系人不存在时执行查找。 我还尝试使用NSCache而不是dictionary,但在需要迭代缓存时遇到了问题

我截断了与主题无关的函数,但希望仍能传达这种方法

import Contacts

extension CNContactStore {

    // Used to seed a Contact Cache with all identifiers
    func getAllIdentifiers() -> [String: CNContact]{

        // keys to fetch from store
        let minimumKeys: [CNKeyDescriptor] = [
            CNContactPhoneNumbersKey as CNKeyDescriptor,
            CNContactIdentifierKey as CNKeyDescriptor
        ]

        // contact request
        let request = CNContactFetchRequest(keysToFetch: minimumKeys)

        // dictionary to hold results, phone number as key
        var results: [String: CNContact] = [:]

        do {
            try enumerateContacts(with: request) { contact, stop in

                for phone in contact.phoneNumbers {
                    let phoneNumberString = phone.value.stringValue
                    results[phoneNumberString] = contact
                }
            }
        } catch let enumerateError {
            print(enumerateError.localizedDescription)
        }

        return results
    }

    // retreive a contact using an identifier
    // fetch keys lists any CNContact Keys you need
    func get(withIdentifier identifier: String, keysToFetch: [CNKeyDescriptor]) -> CNContact? {

        var result: CNContact?
        do {
            result = try unifiedContact(withIdentifier: identifier, keysToFetch: keysToFetch)
        } catch {
            print(error)
        }

        return result
    }
}

final class ContactsCache {

    static let shared = ContactsCache()

    private var cache : [String : ContactCacheItem] = [:]

    init() {

        self.initializeCache()  // calls CNContactStore().getAllIdentifiers() and loads into cache

        NotificationCenter.default.addObserver(self, selector: #selector(contactsAppUpdated), name: .CNContactStoreDidChange, object: nil)
    }

    private func initializeCache() {

        DispatchQueue.global(qos: .background).async {

            let seed = CNContactStore.getAllIdentifiers()

            for (number, contact) in seed{

                let item = ContactCacheItem.init(contact: contact, phoneNumber: number )
                self.cache[number] = item
            }
        }
    }

    // if the contact is in cache, return immediately, else fetch and execute completion when finished. This is bit wonky to both return value and execute completion, but goal was to reduce visible cell async update as much as possible
    public func contact(for phoneNumber: String, completion: @escaping (CNContact?) -> Void) -> CNContact?{

        if !initialized {   // the cache has not finished seeding, queue request

            queueRequest(phoneNumber: phoneNumber, completion: completion)  // save request to be executed as soon as seeding completes
            return nil
        }

        // item is in cache
        if let existingItem = getCachedContact(for: phoneNumber) {

            // is it being looked up
            if existingItem.lookupInProgress(){
                existingItem.addCompletion(completion: completion)
            }
            // is it stale or has it never been looked up
            else if existingItem.shouldPerformLookup(){

                existingItem.addCompletion(completion: completion)
                refreshCacheItem( existingItem )
            }
            // its current, return it
            return existingItem.contact
        }

        // item is not in cache
        completion(nil)
        return nil
    }

    private func getCachedContact(for number: String) -> ContactCacheItem?  {
        return self.cache.first(where: { (key, _) in key.contains( number) })?.value
    }


    // during the async initialize/seeding of the cache, requests may come in from app, so they are temporarily 'queued'
    private func queueRequest(phoneNumber: String, completion: @escaping (CNContact?) -> Void){..}
    // upon async initialize/seeding completion, queued requests can be executed
    private func executeQueuedRequests() {..}
    // if app receives notification of update to user contacts, refresh cache
    @objc func contactsAppUpdated(_ notification: Notification) {..}
    // if a contact has gone stale or never been fetched, perform the fetch
    private func refreshCacheItem(_ item: ContactCacheItem){..}
    // if app receives memory warning, dump data
    func clearCaches() {..}
}

class ContactCacheItem : NSObject {

    var contact: CNContact? = nil
    var lookupAttempted : Date?  // used to determine when last lookup started
    var lookupCompleted : Date?  // used to determien when last successful looup completed
    var phoneNumber: String     //the number used to look this item up
    private var callBacks = ContactLookupCompletion()  //used to keep completion blocks for lookups in progress, in case multilpe callers want the same contact info

    init(contact: CNContact?, phoneNumber: String){..}
    func updateContact(contact: CNContact?){..}  // when a contact is fetched from store, update it here
    func lookupInProgress() -> Bool {..}
    func shouldPerformLookup() -> Bool {..}
    func hasCallBacks() -> Bool {..}
    func addCompletion(completion: @escaping (CNContact?) -> Void){..}
}

我还没有在CNContactStore的Apple文档页面上找到任何清晰的示例,即先获取标识符,然后批量获取其他密钥。@Augie完全正确。我自己也在想这件事。如果没有实际的方法,为什么他们会在文档中提到这一点。今天早上我更新了我的联系人缓存机制。主要的变化是预先获取所有标识符,然后根据应用程序的需要惰性地获取联系人。速度更快,但没有进行实际性能测试。。我使用电话号码作为键,值是一个自定义类,其中包含cncontact以及我的ContactsCache类使用的其他属性,主要用于了解是否已经执行了提取以及提取的时间。它感觉比它应该的更难,必须观察CNContactStoreDidChange,在初始种子设定发生时拥有队列来保存查找请求,以及竞争cases@Augie您能在这里添加一个代码示例吗?
import Contacts

extension CNContactStore {

    // Used to seed a Contact Cache with all identifiers
    func getAllIdentifiers() -> [String: CNContact]{

        // keys to fetch from store
        let minimumKeys: [CNKeyDescriptor] = [
            CNContactPhoneNumbersKey as CNKeyDescriptor,
            CNContactIdentifierKey as CNKeyDescriptor
        ]

        // contact request
        let request = CNContactFetchRequest(keysToFetch: minimumKeys)

        // dictionary to hold results, phone number as key
        var results: [String: CNContact] = [:]

        do {
            try enumerateContacts(with: request) { contact, stop in

                for phone in contact.phoneNumbers {
                    let phoneNumberString = phone.value.stringValue
                    results[phoneNumberString] = contact
                }
            }
        } catch let enumerateError {
            print(enumerateError.localizedDescription)
        }

        return results
    }

    // retreive a contact using an identifier
    // fetch keys lists any CNContact Keys you need
    func get(withIdentifier identifier: String, keysToFetch: [CNKeyDescriptor]) -> CNContact? {

        var result: CNContact?
        do {
            result = try unifiedContact(withIdentifier: identifier, keysToFetch: keysToFetch)
        } catch {
            print(error)
        }

        return result
    }
}

final class ContactsCache {

    static let shared = ContactsCache()

    private var cache : [String : ContactCacheItem] = [:]

    init() {

        self.initializeCache()  // calls CNContactStore().getAllIdentifiers() and loads into cache

        NotificationCenter.default.addObserver(self, selector: #selector(contactsAppUpdated), name: .CNContactStoreDidChange, object: nil)
    }

    private func initializeCache() {

        DispatchQueue.global(qos: .background).async {

            let seed = CNContactStore.getAllIdentifiers()

            for (number, contact) in seed{

                let item = ContactCacheItem.init(contact: contact, phoneNumber: number )
                self.cache[number] = item
            }
        }
    }

    // if the contact is in cache, return immediately, else fetch and execute completion when finished. This is bit wonky to both return value and execute completion, but goal was to reduce visible cell async update as much as possible
    public func contact(for phoneNumber: String, completion: @escaping (CNContact?) -> Void) -> CNContact?{

        if !initialized {   // the cache has not finished seeding, queue request

            queueRequest(phoneNumber: phoneNumber, completion: completion)  // save request to be executed as soon as seeding completes
            return nil
        }

        // item is in cache
        if let existingItem = getCachedContact(for: phoneNumber) {

            // is it being looked up
            if existingItem.lookupInProgress(){
                existingItem.addCompletion(completion: completion)
            }
            // is it stale or has it never been looked up
            else if existingItem.shouldPerformLookup(){

                existingItem.addCompletion(completion: completion)
                refreshCacheItem( existingItem )
            }
            // its current, return it
            return existingItem.contact
        }

        // item is not in cache
        completion(nil)
        return nil
    }

    private func getCachedContact(for number: String) -> ContactCacheItem?  {
        return self.cache.first(where: { (key, _) in key.contains( number) })?.value
    }


    // during the async initialize/seeding of the cache, requests may come in from app, so they are temporarily 'queued'
    private func queueRequest(phoneNumber: String, completion: @escaping (CNContact?) -> Void){..}
    // upon async initialize/seeding completion, queued requests can be executed
    private func executeQueuedRequests() {..}
    // if app receives notification of update to user contacts, refresh cache
    @objc func contactsAppUpdated(_ notification: Notification) {..}
    // if a contact has gone stale or never been fetched, perform the fetch
    private func refreshCacheItem(_ item: ContactCacheItem){..}
    // if app receives memory warning, dump data
    func clearCaches() {..}
}

class ContactCacheItem : NSObject {

    var contact: CNContact? = nil
    var lookupAttempted : Date?  // used to determine when last lookup started
    var lookupCompleted : Date?  // used to determien when last successful looup completed
    var phoneNumber: String     //the number used to look this item up
    private var callBacks = ContactLookupCompletion()  //used to keep completion blocks for lookups in progress, in case multilpe callers want the same contact info

    init(contact: CNContact?, phoneNumber: String){..}
    func updateContact(contact: CNContact?){..}  // when a contact is fetched from store, update it here
    func lookupInProgress() -> Bool {..}
    func shouldPerformLookup() -> Bool {..}
    func hasCallBacks() -> Bool {..}
    func addCompletion(completion: @escaping (CNContact?) -> Void){..}
}