Skip to content

Instantly share code, notes, and snippets.

@krin-san
Last active August 29, 2015 14:18
Show Gist options
  • Save krin-san/402f5b23ee1e2c8c73ec to your computer and use it in GitHub Desktop.
Save krin-san/402f5b23ee1e2c8c73ec to your computer and use it in GitHub Desktop.
Gist for creating test contacts in iOS AddressBook
#import <AddressBook/AddressBook.h>
...
void (^addContacts)(NSInteger) = ^(NSInteger count){
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
for (int i = 0; i < count; i++) {
// create an ABRecordRef
ABRecordRef record = ABPersonCreate();
NSString *fname = [NSString stringWithFormat:@"Name %i", i];
NSString *lname = [NSString stringWithFormat:@"Last %i", i];
NSString *phone = [NSString stringWithFormat:@"%lld", (12136310000 + i)];
// add the first name
ABRecordSetValue(record, kABPersonFirstNameProperty, (__bridge CFStringRef)fname, NULL);
// add the last name
ABRecordSetValue(record, kABPersonLastNameProperty, (__bridge CFStringRef)lname, NULL);
// add phone
ABMutableMultiValueRef phones = ABMultiValueCreateMutable(kABPersonPhoneProperty);
ABMultiValueAddValueAndLabel(phones, (__bridge CFStringRef)phone, kABPersonPhoneMobileLabel, NULL);
BOOL isSuccess = ABRecordSetValue(record, kABPersonPhoneProperty, phones, nil);
CFRelease(phones);
// add the record
ABAddressBookAddRecord(addressBook, record, NULL);
}
// save the address book
ABAddressBookSave(addressBook, NULL);
// release
CFRelease(addressBook);
};
void (^removeContacts)(NSInteger) = ^(NSInteger count){
ABAddressBookRef addressBook = ABAddressBookCreateWithOptions(NULL, NULL);
dispatch_semaphore_t sema = dispatch_semaphore_create(0);
ABAddressBookRequestAccessWithCompletion(addressBook, ^(bool granted, CFErrorRef error) {
dispatch_semaphore_signal(sema);
});
dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
CFStringRef nameRef = (__bridge CFStringRef)[NSString stringWithFormat:@"Last"];
CFArrayRef allRecords = ABAddressBookCopyPeopleWithName(addressBook, nameRef);
if (allRecords != NULL) {
int recordsCount = CFArrayGetCount(allRecords);
NSAssert(count == recordsCount, @"We found more contacts than want to remove. Update nameRef to fix it");
for (int i = 0; i < recordsCount; ++i) {
ABRecordRef contact = CFArrayGetValueAtIndex(allRecords, i);
ABAddressBookRemoveRecord(addressBook, contact, nil);
}
}
// save the address book
ABAddressBookSave(addressBook, NULL);
// release
CFRelease(addressBook);
};
//addContacts(1000);
//removeContacts(1000);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment