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

前端 未结 20 1592
[愿得一人]
[愿得一人] 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:02

    Apple actually recommends enumerateContactsWithFetchRequest of CNContactStore to fetch all contacts and NOT unifiedContactsMatchingPredicate.

    Below is the working code for Obj-C.

    CNContactStore *store = [[CNContactStore alloc] init];
    
    //keys with fetching properties
    NSArray *keys = @[CNContactGivenNameKey, CNContactPhoneNumbersKey]; 
    CNContactFetchRequest *request = [[CNContactFetchRequest alloc] initWithKeysToFetch:keys];
    NSError *error;
    
    [store enumerateContactsWithFetchRequest:request error:&error usingBlock:^(CNContact * __nonnull contact, BOOL * __nonnull stop) {
    
            // access it this way -> contact.givenName; etc
    
    }];
    

    Here is the link where apple recommends enumerate function: https://developer.apple.com/reference/contacts/cncontactstore/1403266-unifiedcontactsmatchingpredicate?language=objc#discussion

    If link expired, here is what Apple wrote:

    If no matches are found, this method returns an empty array (or nil in case of error). Use only the predicates from the CNContact class predicates. Compound predicates are not supported by this method. Due to unification, the returned contacts may have different identifiers than you specify. To fetch all contacts, use enumerateContactsWithFetchRequest:error:usingBlock:.

提交回复
热议问题