9

我正在尝试插入var contacts: [CNContact] = []var store = CNContactStore()但我没有找到适合这项工作的代码,我找到了这个函数,我需要给它一个名字

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所有记录,而不仅仅是一个名称相等的记录

4

3 回答 3

12

更新

根据 OP 的评论,请尝试以下基于 CNContactFetchRequest 的 API 来检索所有没有过滤器的联系人。我在后台线程上运行它以减少大量联系人的任何可能问题。

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)

            })
        })
    }

一般来说,您通常会在使用CNContactFetchRequest类时将谓词设置为 nil 以检索所有联系人,而不是按照代码中的描述。

笔记

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

 NSPredicate(value: true)

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

CNContactFetch-谓词

这是您可以修改现有方法的方式:

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()

苹果有一个更简单的示例:

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

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

//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])

联系人框架的更多 Apple 示例

于 2015-10-26T15:05:44.393 回答
10

修改了 Tommie C 对 XCode 8 和 Swift 3.0 的回答。

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

    DispatchQueue.global(qos: .userInitiated).async(execute: { () -> Void in

        let keysToFetch = [CNContactFormatter.descriptorForRequiredKeys(for: .fullName),CNContactPhoneNumbersKey] as [Any] //CNContactIdentifierKey
        let fetchRequest = CNContactFetchRequest( keysToFetch: keysToFetch as! [CNKeyDescriptor])
        var contacts = [CNContact]()
        CNContact.localizedString(forKey: CNLabelPhoneNumberiPhone)

        if #available(iOS 10.0, *) {
            fetchRequest.mutableObjects = false
        } else {
            // Fallback on earlier versions
        }
        fetchRequest.unifyResults = true
        fetchRequest.sortOrder = .userDefault

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


        do {

            try CNContactStore().enumerateContacts(with: 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)
        }

        DispatchQueue.main.async(execute: { () -> Void in
            completionHandler(contacts)

        })
    })
} 

override func viewDidLoad() {
    findContactsOnBackgroundThread { (contacts) in
            self.contactsList = contacts
            self.tableView.reloadData()
        }
}
于 2016-10-01T00:26:52.217 回答
1
/// The default key descriptors to fetch
public var defaultFetchKeys: [String] = [CNContactGivenNameKey,
                                         CNContactFamilyNameKey,
                                         CNContactPhoneNumbersKey,
                                         CNContactImageDataAvailableKey,
                                         CNContactThumbnailImageDataKey]

/**
     Fetch contacts from the user's device

     - parameter sortOrder: The sort order that should be used. Default none.
     - returns: A list of contacts
     */
    public func fetchContacts(withSortOrder sortOrder: CNContactSortOrder = .givenName,
                              qos: DispatchQoS.QoSClass = .background) -> Promise<[Contact]>
    {

        return Promise { seal in

            DispatchQueue.global(qos: qos).async {

                let store = CNContactStore()
                var contacts = [Contact]()

                /// A `PhoneNumberKit` object used to parse and format numbers (expensive!)
                let phoneNumberKit = PhoneNumberKit()

                let request = CNContactFetchRequest(keysToFetch: self.defaultFetchKeys as [CNKeyDescriptor])
                request.sortOrder = sortOrder
                request.unifyResults = true

                do {

                    try store.enumerateContacts(with: request) { contact, _ in

                        if let user = Contact(contact: contact, kit: phoneNumberKit) {
                            contacts.append(user)
                        }

                    }

                    DispatchQueue.main.async {
                        seal.fulfill(contacts)
                    }

                } catch {

                    DispatchQueue.main.async {
                        seal.reject(error)
                    }

                }

            }

        }

    }

我还使用PhoneNumberKit标准化所有数字和PromiseKit链接我的请求,但您几乎可以随意调整它。

于 2019-04-03T12:31:33.770 回答