How to fetch all contacts record in iOS 9 using Contacts Framework

前端 未结 20 1588
[愿得一人]
[愿得一人] 2020-11-28 01:52

Most part of AddressBook framework is deprecated in iOS 9. In the new Contacts Framework documentation only shows how to fetch records matches a NSPredicate, bu

20条回答
  •  攒了一身酷
    2020-11-28 02:08

    For Swift 4

            var results: [CNContact] = []
    
            let fetchRequest = CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey as CNKeyDescriptor, CNContactFamilyNameKey as CNKeyDescriptor, CNContactMiddleNameKey as CNKeyDescriptor, CNContactEmailAddressesKey as CNKeyDescriptor,CNContactPhoneNumbersKey as CNKeyDescriptor])
    
            fetchRequest.sortOrder = CNContactSortOrder.userDefault
    
            let store = CNContactStore()
    
            do {
                try store.enumerateContacts(with: fetchRequest, usingBlock: { (contact, stop) -> Void in
                    print(contact.phoneNumbers.first?.value ?? "no")
                    results.append(contact)
    
                })
            }
            catch let error as NSError {
                print(error.localizedDescription)
            }
    

    Older version for swift var results contains all contact

    let contactStore = CNContactStore()
        var results: [CNContact] = []
        do {
            try contactStore.enumerateContactsWithFetchRequest(CNContactFetchRequest(keysToFetch: [CNContactGivenNameKey, CNContactFamilyNameKey, CNContactMiddleNameKey, CNContactEmailAddressesKey,CNContactPhoneNumbersKey])) {
                (contact, cursor) -> Void in
                results.append(contact)
                }
        }
        catch{
            print("Handle the error please")
        }
    

提交回复
热议问题