Search code examples
iphoneiosaddressbookabaddressbook

Retrieve contacts sorted by Modified date iOS


How can I retrieve all address book contacts which are sorted according to their modified date? i.e. Contact with the latest modified date should come earlier in the list.


Solution

  • As there is no way to directly sort according to the modification date of ABPerson here is something which I think works

    - (NSArray *) getSortedContacts
    {
    
        NSMutableArray * modificationDates = [[NSMutableArray alloc] init];
        NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
        ABAddressBookRef addressBook = ABAddressBookCreate();
        if(addressBook != nil)
        {
            CFIndex nPeople = ABAddressBookGetPersonCount(addressBook);
            if(nPeople > 0)
            {
                CFArrayRef allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook);
                for (int index = 0; index < nPeople; ++index)
                {
                    ABRecordRef person = CFArrayGetValueAtIndex(allPeople, index);
                    NSNumber *contactID = [NSNumber numberWithInt:ABRecordGetRecordID(person)];
                    NSDate *modificationDate = (NSDate*) ABRecordCopyValue(person, kABPersonModificationDateProperty);
                    [modificationDates addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:contactID,modificationDate, nil] forKeys:[NSArray arrayWithObjects:@"contactID",@"modificationDate", nil]]];
                }
                if(allPeople)
                    CFRelease(allPeople);
                allPeople = nil;
            }
        }
        [pool drain];
    
        NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"modificationDate" ascending:TRUE];
        [modificationDates sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
    
        return modificationDates;
    }
    

    when you get the sorted array, get the dictionary from the array and using the contactID and use it to get ABPerson object using this

    ABRecordRef person = ABAddressBookGetPersonWithRecordID(addressbook, (ABRecordID) [[dict valueForKey:@"contactID"] intValue]);
    

    Hope this will help you