如何从不带过滤器的设备中检索所有CNContactStore [英] how to retrive all CNContactStore from device without filter

查看:69
本文介绍了如何从不带过滤器的设备中检索所有CNContactStore的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试插入var contacts: [CNContact] = [] var store = CNContactStore(),但我没有找到适合此工作的正确代码,我发现了需要给该名称起名字的功能

I'm trying to insert into var contacts: [CNContact] = [] the var store = CNContactStore() but I did not find the right code for this job, i found this function that I need to give that a name

func findContactsWithName(name: String) {
    AppDelegate.sharedDelegate().checkAccessStatus({ (accessGranted) -> Void in
        if accessGranted {
            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                do {
                    let predicate: NSPredicate = CNContact.predicateForContactsMatchingName(name)
                    let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactBirthdayKey, CNContactViewController.descriptorForRequiredKeys()]
                    self.contacts = try self.store.unifiedContactsMatchingPredicate(predicate, keysToFetch:keysToFetch)


                    self.tableView.reloadData()
                }
                catch {
                    print("Unable to refetch the selected contact.")
                }
            })
        }
    })
}

我想插入self.contacts所有记录,而不仅是一个名称相等的记录

I want to insert self.contacts all the records and not only one with name equal

推荐答案

更新

基于OP的评论,请尝试使用以下基于CNContactFetchRequest的API来检索所有不带过滤器的联系人.我在后台线程上运行此命令,以减少大量联系人的任何可能的问题.

Based on comment from OP, please try the following CNContactFetchRequest-based API to retrieve all contacts without a filter. I run this on a background thread to reduce any possible issues huge numbers of contacts.

func findContactsOnBackgroundThread ( completionHandler:(contacts:[CNContact]?)->()) {

        dispatch_async(dispatch_get_global_queue(QOS_CLASS_USER_INITIATED, 0), { () -> Void in

            let keysToFetch = [CNContactFormatter.descriptorForRequiredKeysForStyle(.FullName),CNContactPhoneNumbersKey] //CNContactIdentifierKey
            let fetchRequest = CNContactFetchRequest( keysToFetch: keysToFetch)
            var contacts = [CNContact]()
            CNContact.localizedStringForKey(CNLabelPhoneNumberiPhone)

            fetchRequest.mutableObjects = false
            fetchRequest.unifyResults = true
            fetchRequest.sortOrder = .UserDefault

            let contactStoreID = CNContactStore().defaultContainerIdentifier()
            print("\(contactStoreID)")


            do {

                try CNContactStore().enumerateContactsWithFetchRequest(fetchRequest) { (contact, stop) -> Void in
                    //do something with contact
                    if contact.phoneNumbers.count > 0 {
                        contacts.append(contact)
                    }

                }
            } catch let e as NSError {
                print(e.localizedDescription)
            }

            dispatch_async(dispatch_get_main_queue(), { () -> Void in
                completionHandler(contacts: contacts)

            })
        })
    }

通常来说,使用

Generally speaking you would normally set a predicate to nil to retrieve all of the contacts when using CNContactFetchRequest class rather than as described in your code.

注意

如果您想使用现有的API,则建议将谓词设置为true:

If you want to use your existing API then I recommend setting the predicate to true:

 NSPredicate(value: true)

这应该使所有联系人返回.如果这样不起作用,请考虑切换到CNConctactFetchRequest API来枚举联系人.在这种情况下,您可以将谓词设置为nil以获取所有联系人(使用CNConctactFetchRequest).

This should make all contacts return. If that does not work consider switching to the CNConctactFetchRequest API to enumerate the Contacts. In that event you could then set the predicate to nil to fetch all contacts (using CNConctactFetchRequest).

这是修改现有方法的方式:

This is how you might modify the existing method:

func findContacts()->[CNContact] {
        AppDelegate.sharedDelegate().checkAccessStatus({ (accessGranted) -> Void in
            if accessGranted {
                dispatch_async(dispatch_get_main_queue(), { () -> Void in
                    do {
                        let predicate: NSPredicate = NSPredicate(value: true)
                        let keysToFetch = [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactBirthdayKey, CNContactViewController.descriptorForRequiredKeys()]
                        self.contacts = try self.store.unifiedContactsMatchingPredicate(predicate, keysToFetch:keysToFetch)


                        self.tableView.reloadData()
                    }
                    catch {
                        print("Unable to refetch the selected contact.")
                    }
                })
            }
        })
    }

要使用:

let contacts = findContacts()

Apple有一个更简单的示例:

Apple has a simpler sample:

let store = CNContactStore()
let contacts = try store.unifiedContactsMatchingPredicate(CNContact.predicateForContactsMatchingName("Appleseed"), keysToFetch:[CNContactGivenNameKey, CNContactFamilyNameKey])

对于您的用例,您可以尝试像这样修改Apple Sample:

//Use the reference to look up additional keys constants that you may want to fetch
let store = CNContactStore()
let contacts = try store.unifiedContactsMatchingPredicate(NSPredicate(value: true), keysToFetch:[CNContactGivenNameKey, CNContactFamilyNameKey])

查看全文

登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆